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 do lodash and underscore differ in JavaScript?
 - How do I use Lodash to zip two JavaScript arrays together?
 - How can I use Lodash to manipulate JavaScript objects online?
 - How can I use Lodash in JavaScript?
 - How can I use Lodash to remove undefined values from an object in JavaScript?
 - How can I use Lodash to create a unique array in JavaScript?
 - How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
 - How can I use Lodash to union two JavaScript arrays?
 
See more codes...