How do I deep-merge two objects in JavaScript?
Antek N
antek n profile pic

Deep-merging two objects in JavaScript involves combining the properties of both objects into a new object, taking into account nested properties and handling conflicts. Here's a commonly used approach to deep-merge two objects:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

function deepMerge(target, source) {
  if (typeof target !== 'object' || typeof source !== 'object') {
    return source;
  }

  const merged = { ...target };

  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (key in target) {
        merged[key] = deepMerge(target[key], source[key]);
      } else {
        merged[key] = source[key];
      }
    }
  }

  return merged;
}

In this example, thedeepMerge function takes in two objects,target andsource, and recursively merges their properties. It checks if eithertarget orsource is not an object, and if so, returnssource. Then, it creates a shallow copy of thetarget object using the spread operator ({ ...target }) and assigns it to themerged variable. The function then iterates over each property in thesource object using afor...in loop. For each property, it checks if it exists in thetarget object. If the property exists in both objects, it recursively callsdeepMerge on their respective values and assigns the merged result to themerged object. If the property exists only in thesource object, it directly assigns it to themerged object. Here's an example of using thedeepMerge function:

1
2
3
4
5
6

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };

const mergedObj = deepMerge(obj1, obj2);
console.log(mergedObj);

The resultingmergedObj will be:

1
2
3
4
5
6
7
8
9

{
  a: 1,
  b: {
    c: 2,
    d: 3
  },
  e: 4
}

In this example, the properties ofobj2 are deep-merged intoobj1, resulting in a new objectmergedObj with the combined properties from both objects. Keep in mind that this implementation performs a shallow copy of thetarget object. If you need to merge arrays, handle edge cases, or handle specific scenarios, you may need to modify the function accordingly. This approach provides a basic foundation for deep-merging objects, but it may require further customization based on your specific requirements and object structures.