Scale customer reach and grow sales with AskHandle chatbot

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.

image-1
Written by
Published onMay 16, 2025
RSS Feed for BlogRSS Blog

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.

Create your AI Agent

Automate customer interactions in just minutes with your own AI Agent.

Featured posts

Subscribe to our newsletter

Achieve more with AI

Enhance your customer experience with an AI Agent today. Easy to set up, it seamlessly integrates into your everyday processes, delivering immediate results.