Languages
[Edit]
EN

JavaScript - merge two objects properties dynamically

3 points
Created by:
Krzysiek
471

In this article, we would like to show you how to merge two object properties dynamically in JavaScript.

Quick solution:

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

Hint: be careful, presented solutions in this example merged object only on the first level (object1 and object2 direct properties will be combined - without child object properties).

To make full merge it is necessary to iterete grought all objects, or use some library.

 

Practical example

In this example, we merge object1 and object2 into the result object.

1. Merging using ... operator

Spread operator (...) was introduced in ES6.

// ONLINE-RUNNER:browser;

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

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

console.log(JSON.stringify(result, null, 2));

Output:

{
  "1": "a",
  "2": "c",
  "3": "d"
}

Note:

If the property from object2 is the same as property from object1, it will be overwritten.

2. Merging using Object.assign() function

Object.assign() was introduced in ES6.

// ONLINE-RUNNER:browser;

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

const result = Object.assign({}, object1, object2);

console.log(JSON.stringify(result, null, 2));

Note:

If the property from object2 is the same as property from object1, it will be overwritten.

Alternative titles

  1. JavaScript - merging objects (associative arrays)
  2. JavaScript - merge objects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join