arr1:[1,4,5]
arr2:[
{ id: 1, title:'title', body:'body'},
{ id: 2, title:'title', body:'body'},
{ id: 3, title:'title', body:'body'},
{ id: 4, title:'title', body:'body'},
{ id: 5, title:'title', body:'body'},
{ id: 6, title:'title', body:'body'},
]
在React中,如果arr2
中的数字与arr1
中对象的ID相匹配,我将尝试获取arr2
的整个对象。
因此,在此示例中,我试图从arr2
中获得ID为(1,4,5)的每个对象
答案 0 :(得分:3)
您必须过滤匹配其ID的arr2。
const arr1 = [1, 4, 5];
const arr2 = [
{ id: 1, title: "title", body: "body" },
{ id: 2, title: "title", body: "body" },
{ id: 3, title: "title", body: "body" },
{ id: 4, title: "title", body: "body" },
{ id: 5, title: "title", body: "body" },
{ id: 6, title: "title", body: "body" }
];
const result = arr2.filter(item => arr1.includes(item.id));
console.log(result);
答案 1 :(得分:0)
简单地,过滤来自arr1
的具有匹配ID的数据
const arr1 =[1,4,5]
const arr2 =[
{ id: 1, title:'title', body:'body'},
{ id: 2, title:'title', body:'body'},
{ id: 3, title:'title', body:'body'},
{ id: 4, title:'title', body:'body'},
{ id: 5, title:'title', body:'body'},
{ id: 6, title:'title', body:'body'},
];
function findMatchData(sourceData, match) {
return sourceData.filter((current) => {
return match.includes(current.id)
});
}
console.log(findMatchData(arr2, arr1))
希望对您有帮助!
答案 2 :(得分:0)
您可以将功能Array.prototype.filter()
与功能Array.prototype.includes
一起使用,以通过id
过滤所需的对象。
let arr1 = [1,4,5],
arr2 = [{ id: 1, title:'title', body:'body'},{ id: 2, title:'title', body:'body'},{ id: 3, title:'title', body:'body'},{ id: 4, title:'title', body:'body'},{ id: 5, title:'title', body:'body'},{ id: 6, title:'title', body:'body'}],
result = arr2.filter(({id}) => arr1.includes(id));
console.log(result);
答案 3 :(得分:0)
让我在这里提供reduce()
和find()
组合的另一种解决方案。
reduce()方法在数组的每个元素上执行一个reducer函数(由您提供),从而产生单个输出值。
find()方法返回提供的数组中满足提供的测试功能的第一个元素的值。
尝试以下操作:
const arr1 = [1,4,5];
const arr2 = [
{ id: 1, title:'title', body:'body'},
{ id: 2, title:'title', body:'body'},
{ id: 3, title:'title', body:'body'},
{ id: 4, title:'title', body:'body'},
{ id: 5, title:'title', body:'body'},
{ id: 6, title:'title', body:'body'},
];
const result = arr2.reduce((a, {id,body}) => {
if (arr1.find(e => id === e)) a.push({id, body});
return a;
}, []);
console.log(result);
希望对您有帮助!