Use recursively merge arbitrarily deep objects into arrays to merge objects without overwriting in JavaScript. See a code example with a detailed explanation.
Or you can use the Object.assign()
method or the spread syntax (...
) along with a combination of Array.prototype.reduce()
and Object.entries()
. Here are examples of both approaches:
Using Object.assign()
:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj);
// Output: { a: 1, b: 3, c: 4 }
Using reduce()
and Object.entries()
:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = [obj1, obj2].reduce((result, current) => {
Object.entries(current).forEach(([key, value]) => {
if (!result.hasOwnProperty(key)) {
result[key] = value;
}
});
return result;
}, {});
console.log(mergedObj);
// Output: { a: 1, b: 2, c: 4 }
JavaScript merges objects without overwriting
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
function deepmerge_inh(foo, bar) {
var merged = {};
for (var each in bar) {
if (each in foo) {
if (typeof(foo[each]) == "object" && typeof(bar[each]) == "object") {
merged[each] = deepmerge(foo[each], bar[each]);
} else {
merged[each] = [foo[each], bar[each]];
}
} else {
merged[each] = bar[each];
}
}
for (var each in foo) {
if (!(each in bar)) {
merged[each] = foo[each];
}
}
return merged;
}
var foo = {
a : 1,
b : 2
};
var bar = {
a : 3,
b : 4
}
var res = deepmerge_inh(foo,bar)
console.log(res)
</script>
</body>
</html>
Output:
Source: stackoverflow.com
You can do it with Object.assign()
, which is the internal language structure:
const o1 = {a: 1, b: 1, c:1};
const o2 = {b:5};
const o3 = Object.assign({}, o1, o2);
result:
o1: {a: 1, b: 1, c:1};
o2: {b: 5};
o3: {a: 1, b: 5, c:1};
Updated:
With ES6 you can do it more prettily by using spread:
const o3 = {...o1, ...o2}
You will create a new object with properties from o1 merged with properties from o2 and updated from o2 on conflict properties names. This construction also doesn’t need any extra libs or modules.
Another example
function mergeObjects(...objects) {
const isObject = (obj) => obj && typeof obj === "object";
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach((key) => {
const pVal = prev[key];
const oVal = obj[key];
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal);
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = mergeObjects(pVal, oVal);
} else {
prev[key] = oVal;
}
});
return prev;
}, {});
}
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const obj3 = { f: 5 };
const merged = mergeObjects(obj1, obj2, obj3);
console.log(merged); // { a: 1, b: { c: 2, d: 3 }, e: 4, f: 5 }
Comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version