Javascript 如何根据其他数组中的项目筛选数组?
我有两个数组,我想根据第一个数组中的内容过滤第二个数组Javascript 如何根据其他数组中的项目筛选数组?,javascript,Javascript,我有两个数组,我想根据第一个数组中的内容过滤第二个数组 const items = [{itemid: 1, itemname: "hello world"}, {itemid: 2, itemname: "test"}] const links = [{source: 1, target 2}, {source: 3, target: 4}] //desired output filteredLinks = [{source: 1, target: 2
const items = [{itemid: 1, itemname: "hello world"}, {itemid: 2, itemname: "test"}]
const links = [{source: 1, target 2}, {source: 3, target: 4}]
//desired output
filteredLinks = [{source: 1, target: 2}]
在本例中,由于{source:3,target:4}
与items
中的任何itemid
值都不匹配,因此我希望在新数组filteredLinks
中筛选出该对象。我想我可以通过迭代项
来找到匹配项,但它没有返回任何内容
let filteredLinks = links.filter((i) =>
i.source.includes(
items.forEach((x) => {
return x.itemid;
})
) ||
i.target.includes(
items.forEach((x) => {
return x.itemid;
})
)
)
有没有什么方法可以达到类似我正在尝试的效果
const项=[{
项目编号:1,
项目名称:“你好,世界”
}, {
项目编号:2,
项目名称:“测试”
}]
常量链接=[{
资料来源:1,
目标:2
}, {
资料来源:3,
目标:4
}]
const id=items.map(item=>item.itemid);//将产生并排列[1,2]
常量filteredLinks=links.filter(link=>ids.includes(link.source))
log(filteredLinks)
与其他解决方案不同,此解决方案检查源和目标
const项=[{
项目编号:1,
项目名称:“你好,世界”
}, {
项目编号:2,
项目名称:“测试”
}]
常量链接=[{
资料来源:1,
目标:2
}, {
资料来源:3,
目标:4
}]
const id=items.map(item=>item.itemid);
常量filteredLinks=links.filter((obj)=>{
for(Object.entries(obj))的常量[key,value]{
if(ID.包括(值)){
返回obj;
}
}
})
console.log(filteredLinks)