Merge two objects deeply nested in Javascript

RAJA S
2 min readSep 17, 2022

In this blog, you will learn how two objects can be merged deeply nested objects. Javascript is offering Object.assign() and Spread Operator to merge the objects. But they does merge objects shallow only not deeply.

I have found a solution for merging deeply nested objects with the recursive function.

Recursion

Recursive function calls itself until condition met

Recursion Example:

const factorial = (n) => {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
};
console.log(factorial(10));

Merge nested objects deeply:

I have created a function named deepMergeObject and It has two parameters called targetObject and sourceObject. To avoid the mutation, I have cloned deeply both objects with the help of JSON.parse and JSON.stringify.

Iterating the sourceObject, when the property value is other than object type, It will be merged into the targetObject. If the property value is object type, we are invoking the deepMergeObject function recursively.

we have created two objects named targetPerson and sourcePerson. Whatever properties we are passing into the sourcePerson, it will be merged into the targetPerson.

We have passed airlines and jobs nested properties in the sourcePerson. You can see below how our deepMergeFunction merged two objects very nicely.

Code Snippets

Conclusion:

I hope this blog would help you when you are working on merging two objects.

--

--