How can I merge properties of two JavaScript objects dynamically?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' }
raja
Published on 24-Oct-2020 15:53:28
Advertisements