How to merge properties of two JavaScript objects dynamically?
Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows the privilege to obtain a list of parameters from an array.
Javascript objects are key-value paired dictionaries. We can merge different objects into one using the spread (…) operator.
Syntax:
object1 = {...object2, ...object3, ... }
Example 1:
<script> let A = { name: "geeksforgeeks", }; let B = { }; let Sites = { ...A, ...B }; console.log(Sites) </script> |
Output:

Example 2: Suppose the objects have the same keys. In this case, the value of the key of the object which appears later in the distribution is used.
<script> let A = { name: "geeksforgeeks", }; let B = { name: "wordpress"}; let Sites = { ...A, ...B }; console.log(Sites) </script> |
Output:

Another method: We can also use the Object.assign() method to merge different objects.
Example:
<script> let A = { name: "geeksforgeeks", }; let B = { }; let Sites = Object.assign(A, B); console.log(Sites); </script> |
Output:

Recommended Posts:
- How to create an image element dynamically using JavaScript ?
- How to merge two PHP objects?
- How to get the javascript function parameter names/values dynamically?
- How to change style attribute of an element dynamically using JavaScript ?
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- JavaScript | Object Properties
- How to get a subset of a javascript object's properties?
- How to get font properties of particular element in JavaScript ?
- JavaScript | Window innerWidth and innerHeight Properties
- Objects in Javascript
- JavaScript | Objects
- JavaScript | Date Objects
- Max/Min value of an attribute in an array of objects in JavaScript
- Creating objects in JavaScript (3 Different Ways)
- How to remove Objects from Associative Array in JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



