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 do I use Lodash in a JavaScript playground?
- How do lodash and JavaScript differ in terms of usage in software development?
- How do I use Lodash to zip two JavaScript arrays together?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use an online JavaScript compiler with Lodash?
- How can I use Lodash to find the unique key of a JavaScript object?
- How can I use Lodash to manipulate JavaScript objects online?
- How do I use Lodash in JavaScript?
- How can I use lodash in a JavaScript sandbox?
See more codes...