How to merge properties of two JavaScript objects dynamically
Overview
In JavaScript, we can merge the properties of two objects dynamically using the following approaches.
- Spread (
...) operator Object.assign()method
Using the spread (...) operator
We can merge the properties of two objects using the spread operator as below:
Syntax
const obj3 = {...obj1,...obj2}
Syntax of Spread Operator
Example 1
// creating object 1const obj1 = {name: 'Shubham'}// creating object 2const obj2 = {designation: 'Software Engineer'}// merging obj1 and obj2const obj3 = {...obj1,...obj2}// printing obj3 on consoleconsole.log(obj3);
Explanation
- Lines 2–4: We create an object
obj1. - Lines 7–9: We create another object
obj2. - Lines 12–15: We merge the properties of
obj1andobj2using the spread operator and store them in the objectobj3. - Line 18: We print
obj3on the console.
Note: If both the objects have a similar key then the value of the key of the object that appeared last is used.
Using the Object.assign()method
We can merge the properties of two objects using the Object.assign() method as below:
Syntax
const obj3 = Object.assign(obj1, obj2);
Syntax of Spread Operator
Example 2
// creating object 1const obj1 = {name: 'Shubham'}// creating object 2const obj2 = {designation: 'Software Engineer'}// merging obj1 and obj2const obj3 = Object.assign(obj1, obj2);// printing obj3 on consoleconsole.log(obj3);
Explanation
- Lines 2-4: We create an object
obj1. - Lines 7-9: We create another object
obj2. - Line 12: We merge the properties of
obj1andobj2using theObject.assign()method and store them in the objectobj3. - Line 15: We print
obj3on the console.