In JavaScript, we can merge the properties of two objects dynamically using the following approaches.
...) operatorObject.assign() method...) operatorWe can merge the properties of two objects using the spread operator as below:
const obj3 = {...obj1,...obj2}
// 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);
obj1.obj2.obj1 and obj2 using the spread operator and store them in the object obj3.obj3 on 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.
Object.assign()methodWe can merge the properties of two objects using the Object.assign() method as below:
const obj3 = Object.assign(obj1, obj2);
// 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);
obj1.obj2.obj1 and obj2 using the Object.assign() method and store them in the object obj3.obj3 on the console.