How to Merge Properties of Two JavaScript Objects Dynamically?
Last Updated :
19 Nov, 2024
Improve
Here are two different ways to merge properties of two objects in JavaScript.
1. Using Spread Operator
The 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 value is expected. It allows the privilege to obtain a list of parameters from an array. Javascript objects are key-value paired dictionaries.
Syntax
object1 = {...object2, ...object3, ... }
let A = {
name: "geeksforgeeks",
};
let B = {
domain: "https://geeksforgeeks.org"
};
let Sites = { ...A, ...B };
console.log(Sites)
Output
{ name: 'geeksforgeeks', domain: 'https://geeksforgeeks.org' }
2. Using Object.assign() Method
We can also use the Object.assign() method to merge different objects. that function helps us to merge the two different objects.
let A = {
name: "geeksforgeeks",
};
let B = {
domain: "https://geeksforgeeks.org"
};
let Sites = Object.assign(A, B);
console.log(Sites);
Output
{ name: 'geeksforgeeks', domain: 'https://geeksforgeeks.org' }