Merge Two Objects in JavaScript

Cover Image for Merge Two Objects in JavaScript

There are several ways to merge two JavaScript objects together:

  1. Use the ES6 spread operator, ... [recommended]
  2. Use Object.assign()
  3. Use a for...in statement to iterate over an object's enumerable properties

The ES6 spread operator provides a simple syntax - it's a great option for most use cases. However, there may be times when Object.assign()'s explicitness feels more appropriate.

The for...in statement may be required by older applications that lack modern build processes. While this approach is good to be familiar with, it's not the most common or ideal.

Simplicity and readability are at the center of clean code. Use your discretion when selecting an approach appropriate for your application.

1. Use the ... spread operator to merge objects

ES6 introduced a spread operator which simplifies combining objects.

We can use the spread operator to merge the properties of one or more objects onto another. The spread operator can also be used to create a new object with properties merged from one or more other objects.

Create a new object with properties combined from other objects

const person = {
  firstName: 'Dwight',
  lastName: 'Schrute',
  dateOfBirth: '01-01-1980',
};

const jobInfo = {
  manager: 'Michael Scott',
  jobTitle: 'Assistant to the Regional Manager',
  office: 'Scranton, PA',
  fullTime: true,
};

const employee ={
  ...person,
  ...jobInfo
};

console.log(employee);

The above code outputs:

{
  "firstName": "Dwight",
  "lastName": "Schrute",
  "dateOfBirth": "01-01-1980",
  "manager": "Michael Scott",
  "jobTitle": "Assistant to the Regional Manager",
  "office": "Scranton, PA",
  "fullTime": true
}

Merge one object's properties onto another object

In some cases, we may want to merge properties from one object onto another.

const jobInfo = {
  manager: 'Michael Scott',
  jobTitle: 'Assistant to the Regional Manager',
  office: 'Scranton, PA',
  fullTime: true,
};

const person = {
  firstName: 'Dwight',
  lastName: 'Schrute',
  dateOfBirth: '01-01-1980',
  ...jobInfo, // Merge `jobInfo` onto the `person` object
};

console.log(person);

Outputs:

{
  "firstName": "Dwight",
  "lastName": "Schrute",
  "dateOfBirth": "01-01-1980",
  "manager": "Michael Scott",
  "jobTitle": "Assistant to the Regional Manager",
  "office": "Scranton, PA",
  "fullTime": true
}

2. Use Object.assign() to merge two JavaScript objects

The simplest way to merge two objects together is using the built-in Object.assign() function.

Here's an example of how we can combine the properties from objectA and objectB into a new object:

const objectA = { color: 'blue' };
const objectB = { material: 'cotton' };

const mergedObject = Object.assign({}, objectA, objectB);

console.log(mergedObject);
// { color: 'blue', material: 'cotton' }

// Note that the original objects are not mutated,
// their original values are unchanged
console.log(objectA);
// { color: 'blue' }

console.log(objectB);
// { material: 'cotton' }

Merge multiple JavaScript objects

It's also possible to merge multiple JavaScript objects together by using Object.assign().

Here's an example:

const objects = [
  { color: 'blue' },
  { type: 'shirt' },
  { material: 'cotton' },
  { style: 'polo' },
];

// Use the es6 spread operator to pass each object within the
// `objects` array
const mergedObject = Object.assign({}, ...objects);

console.log(mergedObject);

See that all four of the original objects have been merged into a single new object:

{
  color: 'blue',
  type: 'shirt',
  material: 'cotton',
  style: 'polo',
}

Merge one object into another object

In the above example we pass an empty {} as the first argument to Object.assign(). Doing so prevents new values from being added to any of the original objects.

In some cases, we may want to update the original object by merging a new object into it.

Here's how we can use Object.assign() to merge properties from one object onto another:

const objectA = { color: 'blue' };
const objectB = { type: 'shirt' };

Object.assign(objectA, objectB);

console.log(objectA);
// { "color": "blue", "type": "shirt" }

Merging objects with the same properties

It's important to keep in mind that merging two objects with the same properties will overwrite the original.

In the next example, objectB overwrite's objectA's color property with the value "red":

const objectA = { color: 'blue 🔵' };
const objectB = { color: 'red 🔴' };

Object.assign(objectA, objectB);

console.log(objectA);
// { "color": "red 🔴" }

When merging multiple objects, the last object with duplicate properties will be assigned to the result.

In the next example, note that purple 🟣 is the targetObject's color value because it is the last object to have its properties merged.

const objects = [
  { color: 'blue 🔵' },
  { color: 'red 🔴' },
  { color: 'green 🟢' },
  { color: 'purple 🟣' },
];

const targetObject = {}

Object.assign(targetObject, ...objects);

console.log("targetObject's color: ", targetObject.color);
// targetObject's color:  purple 🟣

3. Use a for...in statement to merge two objects

You may be unable to use Object.assign to combine two objects depending on your application's age and browser compatibility requirements.

If you can't use Object.assign(), consider using a for...in statement as an alternative:

const objectA = { color: 'blue 🔵' };
const objectB = { type: 'shirt' };

// Iterate over each key in objectB
for (const key in objectB) {
  // Get the value for the key
  const value = objectB[key];
  
  // Add objectB's key & value to objectA
  objectA[key] = value;
}

console.log(objectA);
// {color: 'blue 🔵', type: 'shirt'}