How to Merge Properties of Two JavaScript Objects Dynamically

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method

You would use object spread:

let merged = {...obj1, ...obj2};

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
* Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you're using babel you'll need the babel-plugin-transform-object-rest-spread plugin for it to work.

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}

Can this solution to merge two objects dynamically be simpler?

You can deep clone your object and change the value:

const {cloneDeep, toPath, set} = require('lodash');

const root = {
list: {
first: false,
second: false,
third: false,
forth: false
}
};

const result = cloneDeep(root);
set(result, toPath('list.first'), true);

console.log(JSON.stringify(result, null, 2));

Here is an example (jsfiddle doesn't support require):

const root = {
list: {
first: false,
second: false,
third: false,
forth: false
}
};

const result = _.cloneDeep(root);
_.set(result, _.toPath('list.first'), true);

console.log(JSON.stringify(result, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Merging two javascript objects into one?

Here's a function that's a bit more generic. It propagates through the object and will merge into a declared variable.

const posts = {  '2018-05-11': {    posts: 2  },  '2018-05-12': {    posts: 5  }};const notes = {  '2018-05-11': {    notes: 1  },  '2018-05-12': {    notes: 3  }};
function objCombine(obj, variable) { for (let key of Object.keys(obj)) { if (!variable[key]) variable[key] = {};
for (let innerKey of Object.keys(obj[key])) variable[key][innerKey] = obj[key][innerKey]; }}
let combined = {};objCombine(posts, combined);objCombine(notes, combined);console.log(combined)

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method

You would use object spread:

let merged = {...obj1, ...obj2};

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
* Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you're using babel you'll need the babel-plugin-transform-object-rest-spread plugin for it to work.

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}

How to merge Object values of two Objects

You can use spread operator.

Update :

if obj2 has some properties that obj1 does not have?

Initially i wrote this answer assuming the keys are indexed like 0,1 and so on but as you mentioned in comment this is not the case than you can build a array of keys and than iterate over it as

as very concisely added in comment by @Nick [...Object.keys(obj1), ...Object.keys(obj2)]

let obj1 = {1: { foo: 1 },2: { bar: 2, fooBar: 3 },3: { fooBar: 3 },};let obj2 = {1: { foo: 1, bar: 2 },2: { bar: 2 },};
let keys = [...new Set([...Object.keys(obj1),...Object.keys(obj2)])]let op = {}let merged = keys.forEach(key=>{ op[key] = { ...obj1[key], ...obj2[key] }})console.log(op)

How to combine 2 objects with same properties-Javascript

What you are describing looks more like an array than an object. But if you want an Object with numeric keys, well you can do that:

var obj1 = { id: 33, name: 'abc', date: "12/12/12", type:"11" }var obj2 = { id: 22, name: 'abc1', date: "12/1/13", type: "33" }
let arr = [obj1, obj2]
// turn array into object:let obj_all = {...arr}console.log(obj_all)

Combining the content of multiple objects that have the same key with that key as the property in JavaScript

You can iterate over the object keys and create a new object out of their aggregation.

You can use ES6 spread operator (...) which allows us to quickly copy all or part of an existing array or object into another array or object.

const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } };
const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } };
let resultObject = {};
Object.keys(cat1).map(key => { // iterate over the keys
resultObject = {
...resultObject,
[key]: {...cat1[key], ...cat2[key]} // merge two objects
}
return;
});

console.log(resultObject);

How to merge two array object dynamically in typescript?

You could use this

var array1 = [
{
Name: "BMW car",
id: "BMW",
group: "car",
children: [
{ Name: "320 Mod", id: "320", group: "BMW" },
{ Name: "X3 Mod", id: "X3", group: "BMW" },
{ Name: "X5 Mod", id: "X5", group: "BMW" }
]
}
];

var array2 = [
{
id: "BMW",
description: "parent car BMW",
children: [
{ id: "320", description: "parent car BMW, model 320", },
{ id: "X3", description: "parent car BMW model X3", },
{ id: "X5", description: "parent car BMW Model X5", }
]
}
];

var result = array1.map(el1 => {
var el2 = array2.find(el => el1.id === el.id);
return { ...el1, ...el2, children: el1.children.map(child1 => ({ ...child1, ...el2.children.find(child2 => child2.id === child1.id) })) };
});

console.log(result);


Related Topics



Leave a reply



Submit