Update JavaScript object with another object, but only existing keys?

JavascriptWeb DevelopmentObject Oriented Programming

For this, use hasOwnProperty(). Following is the code −

Example

var markDetails1 ={
   'marks1': 78,
   'marks2': 65
};
var markDetails2 ={
   'marks2': 89,
   'marks3': 90
}
function updateJavaScriptObject(details1, details2) {
   const outputObject = {};
   Object.keys(details1)
   .forEach(obj => outputObject[obj] =
   (details2.hasOwnProperty(obj) ? details2[obj] : details1[obj]));
   return outputObject;
}
console.log(updateJavaScriptObject(markDetails1, markDetails2));

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

node fileName.js.

Here, my file name is demo140.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo140.js
{ marks1: 78, marks2: 89 }
raja
Published on 11-Sep-2020 06:53:30
Advertisements