reactjs - 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?
解决方案
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.
推荐阅读
- ios - RxSwift:数据库事件和不同的调度问题
- amazon-web-services - 不确定为什么上传到 S3 的视频是 0 位
- excel - 有人可以查看我的 Excel 错误并提供有关代码的反馈吗?
- c# - 从另一个视图访问 _Layout 中的按钮
- vue.js - 我可以在 vue.js 中实现 has() 吗?
- java - 导入junit失败
- r - 使用 rbind 组合数据框 + 添加一个单独的列,其中包含各个数据框的名称
- typescript - 可以在 TypeScript 中将元组转换为数组吗?
- elixir - 如何在 Elixir 的地图列表中总结不同键的值
- ansible - Ansible 同步模块错误