Skip to content Skip to sidebar Skip to footer

Compare Nested Objects With Arrays In Javascript And Return Keys Equality

I have two nested objects obj1 and obj2 and I want to compare them and the recursively return an object that for each nested key has a equality-like boolean flag So for a given obj

Solution 1:

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" }

constisObject = v => v !== null && typeof v == "object";

functiongetDifference(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 ofnewSet([...Object.keys(x), ...Object.keys(y)]))
            temp[key] = getDifference(x[key], y[key])

        return temp;
    }
    return x === y;
}

console.log(getDifference(obj1, obj2));

Post a Comment for "Compare Nested Objects With Arrays In Javascript And Return Keys Equality"