2

So let's show it by example. I have to JSONs:

{
    "a": {
        "b": 1,
        "c": 2
    },
    "d": false,
    "e": 15,
    "f": "something important"
}

and

{
    "a": {
        "b": 1,
        "c": 22
    },
    "d": false,
    "e": "fifteen",
    "g": "something new"
}

and the result I want is:

b: 2 => 22
e: 15 => "fifteen"
f(deleted)
g(created) "something new"

So basically I need a simple diff to show what changed in the model that I got from backend, but I'm not sure if I should look for a library or is it easy enough that it's possible to do with one function.

Zbyszek Kisły
  • 2,110
  • 4
  • 26
  • 48

2 Answers2

1

You could check the parts and get a result by checking the nested parts as well.

function getDifference(a, b) {
    return [...new Set([...Object.keys(a), ...Object.keys(b)])].reduce((r, k) => {

        if (a[k] && b[k] && typeof a[k] === 'object' && typeof b[k] === 'object') {
            var temp = getDifference(a[k], b[k]);
            if (temp.length) r.push(...temp.map(([l, ...a]) => [k + ' ' + l, ...a]));
            return r;
        }

        if (k in a && !(k in b)) {
            r.push([k, 'deleted', a[k]]);
            return r;
        }

        if (!(k in a) && k in b) {
            r.push([k, 'created', b[k]]);
            return r;
        }

        if (a[k] === b[k]) return r;

        r.push([k, 'changed', a[k], b[k]]);
        return r;
    }, []);
}



console.log(getDifference(
    { a: { b: 1, c: 2 }, d: false, e: 15, f: "something important" },
    { a: { b: 1, c: 22 }, d: false, e: "fifteen", g: "something new" }
));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Maybe you should try https://www.npmjs.com/package/deep-diff

Really easy to use and provide a detailed diff with filter method and tooling around diff like approving change or not for example.

MathKimRobin
  • 1,268
  • 3
  • 21
  • 52