How to Deep Merge Two Objects in JavaScript ?
Last Updated :
26 Jul, 2024
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.
JavaScript
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
function deepMerge(target, ...sources) {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
deepMerge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return deepMerge(target, ...sources);
}
const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };
const merged = deepMerge({}, obj1, obj2);
console.log(merged);
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.
JavaScript
function isObject(item) {
return item !== null && typeof item === 'object' && !Array.isArray(item);
}
function deepMerge(target, ...sources) {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
const sourceValue = source[key];
if (isObject(sourceValue) && isObject(target[key])) {
target[key] = deepMerge(target[key], sourceValue);
} else {
target[key] = sourceValue;
}
}
}
}
return deepMerge(target, ...sources);
}
const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };
const merged = deepMerge({}, obj1, obj2);
console.log(merged);
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.
JavaScript
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 } }
Similar Reads
How to Create a Nested Object in JavaScript ? JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure. These are the different methods to create nested
4 min read
How to Compare Objects in JavaScript? Comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations. Below are the various approaches to co
3 min read
How to Deep-Freeze an Object in JavaScript? In JavaScript, freezing an object prevents it from being modified. This means you can no longer add, remove, or modify the properties of an object. However, by default, JavaScript's Object.freeze() only freezes the top level of an object, leaving nested objects or arrays mutable. To achieve immutabi
4 min read
How to Deep Merge Two Objects in TypeScript ? Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
4 min read
How to Convert Object to Array in JavaScript? In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to Merge Multiple Array of Object by ID in JavaScript? Merging multiple arrays of objects by a shared key, like ID, in JavaScript, is used when consolidating data from various sources, such as API responses or databases. This process involves combining objects that have the same key into a single object, allowing developers to manage and manipulate comp
4 min read