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 }