How to deep marge two objects in JavaScript?
In JavaScript, merging two objects may seem quite easy. It is quite easy if we are aiming to do a shallow merge. Let’s consider the following two objects:
const obj1 = {a: 1, b: 2, c: {e: 9}}; const obj2 = {b: 3, c: {d: 8}, f: 5};
Shallow merge
If we want to do a shallow merge we can use the spread operator like below:
console.log({...obj1, ...obj2}); // output { "a": 1, "b": 3, "c": { "d": 8 }, "f": 5 }
Deep merge
If we want to do a deep merge we can do it using the following function:
function isObject(item) { return (item && typeof item === 'object' && !Array.isArray(item)); } function mergeDeep(target, source) { let output = Object.assign({}, target); if (isObject(target) && isObject(source)) { Object.keys(source).forEach(key => { if (isObject(source[key])) { if (!(key in target)) Object.assign(output, { [key]: source[key] }); else output[key] = mergeDeep(target[key], source[key]); } else { Object.assign(output, { [key]: source[key] }); } }); } return output; } const obj1 = {a: 1, b: 2, c: {e: 9}}; const obj2 = {b: 3, c: {d: 8}, f: 5}; console.log(mergeDeep(obj1, obj2)); // Output: { "a": 1, "b": 3, "c": { "e": 9, "d": 8 }, "f": 5 }