Open In App

How to Deep Merge Two Objects in JavaScript ?

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Share
1 Like
Like
Report

Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out to be necessary, deep merge is the activity of taking the attributes or features from multiple objects (which have nested objects) and creating a new object with merged values.

These are the following approaches:

Using Recursive Function

The recursive traveling through the items method is employed here in which properties are merged, for the deep merge for nested objects, the function calls itself.

Syntax:

function deepMerge(target, ...sources) {
// Implementation
}

Example: In the example below we will see how we can merge two objects using the Recursive Function approach.


Output
{ a: { b: 1, c: 2 } }

Using Spread Operator

Objects can be shallow copied using the spread operator (...), by combining recursion with spread operators, it is possible to obtain a deep merging of objects.

Syntax:

function deepMerge(target, ...sources) {
// Implementation
}

Example: In the example below we will see how we can merge two objects using Spread Operator approach.


Output
{ a: { b: 1, c: 2 } }

Using Libraries like Lodash

Lodash has a merge function that does deep merging of objects, it handles its edge cases and complexities very well which makes it a dependable choice for deep merging.

Syntax:

import _ from 'lodash';
const mergedObject = _.merge(object1, object2);

Example: In the example below we will see how we can merge two objects using Libraries like Lodash.

import _ from 'lodash';

const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };

const merged = _.merge(obj1, obj2);

console.log(merged);

Output:

{ a: { b: 1, c: 2 } }

Next Article
Article Tags :

Similar Reads