How to merge objects in JavaScript

Intro

To merge two objects in JavaScript, you can use the Object.assign() method. This method takes in two objects as arguments, and returns a new object that combines the properties of the two objects.

Using Object assign method

Here is an example:

const object1 = {
  a: 1,
  b: 2,
  c: 3,
}

const object2 = {
  d: 4,
  e: 5,
  f: 6,
}

const object3 = Object.assign(object1, object2)

console.log(object3) // Output: { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

In the example above, object3 is a new object that combines the properties of object1 and object2. The Object.assign() method copies the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Using the spread operator

You can also use the spread operator (...) to merge objects. The spread operator allows you to expand an iterable (such as an array or an object) into individual elements.

Here is an example:

const object1 = {
  a: 1,
  b: 2,
  c: 3,
}

const object2 = {
  d: 4,
  e: 5,
  f: 6,
}

const object3 = { ...object1, ...object2 }

console.log(object3) // Output: { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

In the example above, object3 is a new object that combines the properties of object1 and object2. The spread operator expands the properties of object1 and object2, and the resulting elements are assigned to a new object. This method is a shorter and cleaner alternative to Object.assign().