Compare nested objects with arrays in JavaScript and return keys equality Compare nested objects with arrays in JavaScript and return keys equality json json

Compare nested objects with arrays in JavaScript and return keys equality


Some tricky recursion can do the job.

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));