Skip to content
Related Articles

Related Articles

How to merge properties of two JavaScript objects dynamically?
  • Last Updated : 22 Apr, 2019

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
let A = {
    name: "geeksforgeeks",
};
  
let B = {
    domain: "https://geeksforgeeks.org"
};
  
let Sites = { ...A, ...B };
  
console.log(Sites)
</script>

chevron_right


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.



filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
let A = {
    name: "geeksforgeeks",
};
  
let B = {
    name: "wordpress"
};
  
let Sites = { ...A, ...B };
  
console.log(Sites)
</script>

chevron_right


Output:

Another method: We can also use the Object.assign() method to merge different objects.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
let A = {
  name: "geeksforgeeks",
};
  
let B = {
};
  
let Sites = Object.assign(A, B);
  
console.log(Sites);
</script>

chevron_right


Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :