M
M
myskypesla2017-05-07 16:17:03
JavaScript
myskypesla, 2017-05-07 16:17:03

How to compare 2 json files?

Hello everyone, I have 2 JSON files that come from different APIs:

the 1st file looks like this:

{
  "data": [
    {
      "id": 1025
    },
    {
      "id": 2000
    },
    {
      "id": 2500
    }
  ]
}


and the 2nd json file looks like this:
{
  "data": [
    {
      "IDNum": 1025,
      "count": 1
    },
    {
      "IDNum": 2000,
      "count": 3
    },
    {
      "IDNum": 2500,
      "count": 2
    }
  ]
}


The logic is this: the 1st file arrives and if the 2nd file contains an object with id 1025, then take the value of the count field from the 2nd file.

If there is a solution using pure javascript, then it will be cool, because. I am writing in vue js.

Thanks in advance to everyone who answers!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2017-05-07
@myskypesla

First prepare the second JSON

var arrmap = {}
for (x in arr['data']) {
  var v = arr['data'][x]
  arrmap[v['IDNum']] = v['count']
}

And then from the first we will look for:
for (x in foo['data']) { 
  var v = foo['data'][x]
  if (arrmap[v['id']]) {
    console.log(arrmap[v['id']])
  }
}

E
Evgeny Kulakov, 2017-05-08
@kulakoff Vue.js

An option to use find to find an entry:

var file2 = data2

var obj = getElement(file2, 1025)
if (obj) console.log(obj.count)

function getElement(file, id) {
 return file['data'].find(el => el.IDNum === id)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question