How can I deeply merge two objects in JavaScript?
When working with JavaScript, especially in projects involving configurations or complex data structures, you often need to combine two objects into one. Sometimes, a simple merge that overwires properties at the top level isn’t enough. Instead, you need to merge objects deeply, combining nested objects as well. This is a common question during technical interviews because deep merging involves understanding recursion, object handling, and sometimes third-party libraries.
A shallow merge using Object.assign() or the spread operator ({...obj1, ...obj2}
) copies only the first level of an object. For example:
Javascript
In this case, the b
property from obj2
overwrites the b
property in obj1
. Notice how the nested object b
is replaced entirely, not merged.
To perform a deep merge, you need to recursively traverse both objects and merge their properties. Here’s a simple implementation of a deep merge function:
Javascript
You can use this function like this:
Javascript
It’s important to note that this implementation modifies the first object you pass to it, so if you want to keep your original objects unchanged, you should pass a copy of the first object, like in the example above ({ ...obj1 }
).
There are also popular utility libraries like Lodash that offer a _.merge()
method, which performs deep merging easily:
Javascript
Using such libraries can simplify your code and improve reliability, especially for more complex cases.