Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何根据其他数组中的项目筛选数组?_Javascript - Fatal编程技术网

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;
                                   })
                                 )
                              )
有没有什么方法可以达到类似我正在尝试的效果

  • 创建允许的ID列表
  • 筛选id在允许id列表中的链接
  • 同样,你可以不用第1步,但基本上你会一遍又一遍地检查项目,这是低效的

    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)