How To Merge Two Objects In Javascript

In this blog post, we are going to learn how to merge two objects in JavaScript using various methods. Merging objects is a common task when working with JavaScript objects, and it is essential to understand the different ways to do it.

Object.assign()

The simplest way to merge two objects is by using the built-in Object.assign() method. This method takes two or more objects as arguments and returns a new object containing the properties from all input objects. The properties are assigned from left to right, and if there are any duplicate properties, the last assigned value will be used.

const obj1 = {
  a: 1,
  b: 2
};

const obj2 = {
  b: 3,
  c: 4
};

const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj); // { a: 1, b: 3, c: 4 }

Note that Object.assign() does not create a deep copy of the input objects. If an object property contains a reference to another object, the reference will be copied, not the object itself.

Spread Operator

Another method to merge two objects is by using the spread operator (…). The spread operator allows you to expand the properties of an object into a new object. This method is especially useful when you want to merge objects with different properties or create a shallow copy of an object.

const obj1 = {
  a: 1,
  b: 2
};

const obj2 = {
  b: 3,
  c: 4
};

const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 3, c: 4 }

Similar to Object.assign(), the spread operator does not create a deep copy of the input objects.

Deep Merge Using a Recursive Function

If you need to merge objects with nested properties, you can use a custom recursive function to perform a deep merge. This function will iterate over the properties of the input objects and merge them accordingly. If a property is an object, the function will be called recursively to merge the nested objects.

function deepMerge(obj1, obj2) {
  const result = { ...obj1 };

  for (const key in obj2) {
    if (obj2.hasOwnProperty(key)) {
      if (typeof obj2[key] === 'object' && !Array.isArray(obj2[key]) && obj2[key] !== null) {
        result[key] = deepMerge(result[key] || {}, obj2[key]);
      } else {
        result[key] = obj2[key];
      }
    }
  }

  return result;
}

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

const obj2 = {
  b: { d: 4, e: 5 },
  f: 6
};

const mergedObj = deepMerge(obj1, obj2);
console.log(mergedObj); // { a: 1, b: { c: 2, d: 4, e: 5 }, f: 6 }

The deepMerge function will create a deep copy of the input objects and their nested properties while merging them.

Conclusion

In this blog post, we have explored different methods to merge two objects in JavaScript. We have seen how to use Object.assign() and the spread operator for shallow merging and how to create a custom recursive function for deep merging. Depending on your use case, you can choose the appropriate method to merge objects in your JavaScript projects.