Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update JavaScript object with another object, but only existing keys?
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 }Advertisements