朋友公司的面试题 ,取出对象中被改变的属性和值
const obj1 = { a: 1, b: 2, c: 4 };
const obj2 = { a: 1, b: 2, c: 5 };
方法1
function testFun(obj1, obj2) {const diff = {};const keys1 = Object.keys(obj1);const keys2 = Object.keys(obj2);const allKyes = keys1.filter((key) => keys2.includes(key));allKyes.forEach((key) => {if (obj1[key] !== obj2[key]) {diff[key] = obj2[key];}});return Object.keys(diff).length > 0 ? diff : null;
}
console.log(testFun(obj1, obj2));
// 打印 {c:5}
方法2
function testFun1(object, other) {let diff = {};let vChildren;for (var key in object) {if (typeof object[key] === "object" && typeof other[key] === "object" && object[key] && other[key]) {vChildren = testFun1(object[key], other[key]);if (Object.keys(vChildren).length > 0) {diff[key] = other[key];}} else if (object[key] !== other[key]) {diff[key] = other[key];}}return diff;
}
console.log(testFun1(obj1, obj2));
// 打印 {c:5}