Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple git-like diff of two JSONs in javascript

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.

like image 666
zbyshekh Avatar asked Aug 07 '26 16:08

zbyshekh


2 Answers

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; }
like image 171
Nina Scholz Avatar answered Aug 09 '26 08:08

Nina Scholz


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.

like image 32
MathKimRobin Avatar answered Aug 09 '26 07:08

MathKimRobin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!