Languages
[Edit]
EN

JavaScript - merge two objects properties dynamically

3 points
Created by:
Krzysiek
741

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

Quick solution:

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

Edit

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

1. Merging using ... operator

Edit

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

Output:

Note:

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

2. Merging using Object.assign() function

Edit

Object.assign() was introduced in ES6.

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
1
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