How can I merge properties of two JavaScript objects dynamically?


To merger properties of two objects, you can use the concept of {...object1,...object2,... N).

Example

Following is the code −

var firstObject = {
   firstName: 'John',
   lastName: 'Smith'
}; 
var secondObject = {
   countryName: 'US'
};
var mergeObject = {...firstObject, ...secondObject};
console.log(mergeObject);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo307.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo307.js
{ firstName: 'John', lastName: 'Smith', countryName: 'US' }

Updated on: 24-Oct-2020

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements