How to Merge Properties of Two JavaScript Objects Dynamically?
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://www.geeksforgeeks.org/"
};
let Sites = { ...A, ...B };
console.log(Sites)
Output
{ name: 'geeksforgeeks', domain: 'https://www.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://www.geeksforgeeks.org/"
};
let Sites = Object.assign(A, B);
console.log(Sites);
Output
{ name: 'geeksforgeeks', domain: 'https://www.geeksforgeeks.org/' }