我们需要编写一个JavaScript函数,该函数接受两个对象(可能是嵌套的),并为第一个对象中存在但第二个对象中不存在的键返回具有键值对的新对象
让我们为该函数编写代码-
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));
输出结果
控制台中的输出将为-
{ firstName: 'Raghav', age: 43 }