javascript-lodashHow can I perform a deep merge in JavaScript without using Lodash?
A deep merge in JavaScript can be performed without using Lodash by using a recursive function to iterate through the objects and properties. The following example code block will merge two objects into one, and overwrite any properties with the same name:
let obj1 = {
a: 1,
b: 2,
c: {
d: 3
}
}
let obj2 = {
a: 4,
b: 5,
c: {
e: 6
}
}
function deepMerge(obj1, obj2) {
let result = {...obj1, ...obj2};
for (let key in result) {
if (typeof result[key] === 'object') {
result[key] = deepMerge(obj1[key], obj2[key]);
}
}
return result;
}
console.log(deepMerge(obj1, obj2));
Output example
{
a: 4,
b: 5,
c: {
d: 3,
e: 6
}
}
Code explanation
- The
let result = {...obj1, ...obj2};line creates a new object with the properties of bothobj1andobj2. - The
for (let key in result) {loop iterates through the properties of theresultobject. - The
if (typeof result[key] === 'object') {condition checks if the property is an object. - The
result[key] = deepMerge(obj1[key], obj2[key]);line passes the corresponding properties ofobj1andobj2to thedeepMerge()function and assigns the returned value to theresultobject.
Helpful links
More of Javascript Lodash
- How do I use yarn to install and use lodash in a JavaScript project?
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash to create a unique array in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How do I use Lodash to get unique values in a JavaScript array?
- How can I use Lodash to capitalize a string in JavaScript?
- How can I use Lodash in a JavaScript REPL?
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How can I use lodash in a JavaScript sandbox?
- How can I remove a value from an array using JavaScript and Lodash?
See more codes...