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

const k1 = { fruit: '🥝' };
const k2 = { fruit: '🥝' };
// Using JavaScript
JSON.stringify(k1) === JSON.stringify(k2); // true
const k1 = { fruit: '🥝' };
const k2 = { fruit: '🥝' };
Object.entries(k1).toString() === Object.entries(k2).toString();
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]));};
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));
output
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));
output

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store