首页 > 解决方案 > how to get the data where id is equal to the id of other json data?

问题描述

I have 2 JSON data. My Objective is to find the id in details.json data and if the id matches with the id of details.json data then it should return the data with contains id else it should return data which should not have an id.

details.json:

var categoryArray = [
      {cid: '1', name: 'Category_1'},
      {cid: '2', name: 'Category_2'},
      {cid: '3', name: 'Category_3'},
      {cid: '4', name: 'Category_4'}
     ];

sample.json :

var sample= {
      {id: '1'},
      {id: '2'},
     };

i've written in this way:

const allIds = res.data.map(el => { return {id: el.id} }) //getting id in category array
if(id===allIds)
{
return res.data;
}
else {
return res.data!==id
}

Can anyone help me to get the data for both the case, if the condition is true then it should return data where id exists otherwise it should return data where id should not exist in the list?

标签: reactjs

解决方案


Here I have created two utilities to get matching and non matching ids.

var categoryArray = [
  { cid: '1', name: 'Category_1' },
  { cid: '2', name: 'Category_2' },
  { cid: '3', name: 'Category_3' },
  { cid: '4', name: 'Category_4' },
]

var sample = [{ id: '1' }, { id: '2' }]

const getMatchingList = (data, ids) => data.filter(cat => ids.some(s => s.id === cat.cid))
const getNonMatchingList = (data, ids) => data.filter(cat => !ids.some(s => s.id === cat.cid))

const matchingList = getMatchingList(categoryArray, sample)
console.log(matchingList)

const nonMatchingList = getNonMatchingList(categoryArray, sample)
console.log(nonMatchingList)

Hope this helps.


推荐阅读