How to merge two objects - JavaScript

Mo Ibra

Mo Ibra

Jan 1, 2023

In this article we will learn how to merge two objects in JavaScript.

It is very common to merge two objects in JavaScript in JavaScript.


Problem

Now we have a problem, which is that we want to merge two or more objects together.

Imagine we have two objects like those:

// Object 1
const object1 = {
    name: "John",
    age: 30,
};

// Object 2
const object2 = {
    country: "USA",
    langs: ["javascript", "python"],
};

And we want to merge two objects to became like this:

const object = {
    name: "John",
    age: 30,
    country: "USA",
    langs: ["javascript", "python"],
};

How to solve this problem?

There's more than one way to solve this problme such as:

  • Using spread operator ...
  • Using Object.assign()

Merge two objects using spread operator ...

We can use spread operator to merge two objects.

Let's see an example:

// Object 1
const object1 = {
    name: "John",
    age: 30,
};

// Object 2
const object2 = {
    country: "USA",
    langs: ["javascript", "python"],
};

// Merge
const merge = { ...object1, ...object2 };

// Result:
console.log(merge);

Output

{
  name: 'John',
  age: 30,
  country: 'USA',
  langs: [ 'javascript', 'python' ]
}

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. (MDN)


Merge two objects using Object.assign()

We can merge two object using Object.assign as well.

Let's see an example:

// Object 1
const object1 = {
    name: "John",
    age: 30,
};

// Object 2
const object2 = {
    country: "USA",
    langs: ["javascript", "python"],
};

// Merge
const merge = Object.assign(object1, object2);

// Result:
console.log(merge);

Output

{
  name: 'John',
  age: 30,
  country: 'USA',
  langs: [ 'javascript', 'python' ]
}

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. (MDN)


Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: