Prem
Prem

Reputation: 5987

How to compare two json arrays using node.js

json1 = 
[{
        "name": "apple"
},
{
        "name": "mango"
},
{
        "name": "orange"
}]

json2 = [{
        "name": "apple"
},
{
        "name": "mango"
}]

I need to compare the two jsons and find out the mismatch between two json-arrays. The expected result is obviously orange. Would you please anyone help me getting this done.

Upvotes: 0

Views: 5510

Answers (2)

Dylan Watt
Dylan Watt

Reputation: 3387

There are some packages out there on npm that appear to do this (https://github.com/NV/objectDiff.js).

If efficiency is not a concern, you can just do a scan, where you loop across json1, and for every element see if it exists in json2, and then vice versa. In this case, since you're only looking for these name KVPs, you could also just normalize it into ['apple', 'mango', 'orange'] and ['apple', 'mango'] and use indexOf().

Upvotes: 1

Randy Hunt
Randy Hunt

Reputation: 425

Grab json-diff from npm - https://www.npmjs.com/package/json-diff

Or, just have a look at the source code and do whatever he did. - https://github.com/andreyvit/json-diff

Upvotes: 1

Related Questions