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 bothobj1
andobj2
. - The
for (let key in result) {
loop iterates through the properties of theresult
object. - 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 ofobj1
andobj2
to thedeepMerge()
function and assigns the returned value to theresult
object.
Helpful links
More of Javascript Lodash
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How can I use Lodash to find and update an object in a JavaScript array?
- How do I use Lodash to truncate a string in JavaScript?
- 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 yarn to install and use lodash in a JavaScript project?
- How can I use Lodash's throttle function in JavaScript?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How do I use Lodash to sort an array of objects by a specific property in JavaScript?
- How can I use Lodash to remove empty properties from an object in JavaScript?
See more codes...