Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Object difference in JavaScript
We are required to write a JavaScript function that takes in two objects (possibly nested) and returns a new object with key value pair for the keys that were present in the first object but not in the second
Let's write the code for this function −
Example
const obj1 = {
"firstName": "Raghav",
"lastName": "Raj",
"age": 43,
"address": "G-12 Kalkaji",
"email": "raghavraj1299@yahoo.com",
"salary": 90000
};
const obj2 = {
"lastName": "Raj",
"address": "G-12 Kalkaji",
"email": "raghavraj1299@yahoo.com",
"salary": 90000
};
const objectDifference = (first, second) => {
return Object.keys(first).reduce((acc, val) => {
if(!second.hasOwnProperty(val)){
acc[val] = first[val];
};
return acc;
}, {});
};
console.log(objectDifference(obj1, obj2));
Output
The output in the console will be −
{ firstName: 'Raghav', age: 43 } Advertisements
