Compare 2 Nested Objects in JavaScript [IMP]| Apple Coding Interview

1] Using JSON.stringify
,[does not work for nested objects]
const k1 = { fruit: '🥝' };
const k2 = { fruit: '🥝' };// Using JavaScript
JSON.stringify(k1) === JSON.stringify(k2); // true
2] Using Object.entries,
[does not work for nested objects]
const k1 = { fruit: '🥝' };
const k2 = { fruit: '🥝' };Object.entries(k1).toString() === Object.entries(k2).toString();
3] Deep equality comparison [nested object comparison]
const equals = (a, b) => { if (a === b) return true; if (a instanceof Date && b instanceof Date)
return a.getTime() === b.getTime(); if (!a || !b || (typeof a !== 'object' && typeof b !== 'object'))
return a === b; if (a.prototype !== b.prototype) return false; const keys = Object.keys(a); if (keys.length !== Object.keys(b).length) return false;return keys.every(k => equals(a[k], b[k]));};
OR
var obj1 = { prop1: 1, prop2: "foo", prop3: [{ number: 1, prop4: "foo", prop5: "a" }, { number: 2, prop4: "foo", prop5: "b" }] }var obj2 = { prop1: 3, prop2: "foo", prop3: [{ number: 1, prop4: "bar", prop5: "b" }, { number: 2, prop4: "foo", prop5: "a" }, { number: 3, prop4: "foo", prop5: "e" }], prop6: "new" }const isObject = v => v !== null && typeof v == "object";function getDifference(x, y = x) {
if (x === undefined) x = y; if (Array.isArray(x) && Array.isArray(y)) {
const temp = [];
for (let i = 0; i < (x.length + y.length) / 2; i++)
temp.push(getDifference(x[i], y[i])) return temp;
} if (isObject(x) && isObject(y)) {
const temp = {};
for (const key of new Set([...Object.keys(x), ...Object.keys(y)]))
temp[key] = getDifference(x[key], y[key]) return temp;
}
return x === y;
}console.log(getDifference(obj1, obj2));

OR ,
- Array.from(…) — Array.from([1, 2, 3], x => x + x)
- new Set([...Object.keys(a), ...Object.keys(b)])
, return [“prop1, “prop2”, “prop3”, “prop4”]
- k => ({ [k]: true/false }) // callback
const isObject = v => v && typeof v === 'object';
function getDifference(a, b) {
return Object.assign(...Array.from(
new Set([...Object.keys(a), ...Object.keys(b)]),
k => ({ [k]: isObject(a[k]) && isObject(b[k])
? getDifference(a[k], b[k])
: a[k] === b[k]
})
));
}
var obj1 = { prop1: 1, prop2: "foo", prop3: { prop4: 2, prop5: "bar" } };var obj2 = { prop1: 3, prop2: "foo", prop3: { prop4: 2, prop5: "foobar" }, prop6: "new" };
console.log(getDifference(obj1, obj2));
