javascript如果键不存在,则从对象数组中删除元素

时间:2020-05-19 18:24:24

标签: javascript arrays

我必须按键值比较2个数组。如果“链接”数组中的“目标”或“源”不是“节点”数组中的“ id”之一,则必须从“链接”中删除相应的数组。

来自:

{
    "nodes":[
        {
            "id": b,
            "year": 3
        },
        {
            "id": c,
            "year": 1
        },
                {
            "id": d,
            "year": 2
        }
    ],
    "links":[
        {
            "source": a,
            "target": b
        },
        {
            "source": a,
            "target": c
        },
        {
            "source": b,
            "target": a
        }
        {
            "source": c,
            "target": d
        }
    ]
}

结果:

{
    "nodes":[
        {
            "id": b,
            "year": 3
        },
        {
            "id": c,
            "year": 1
        },
                {
            "id": d,
            "year": 2
        }
    ],
    "links":[
        {
            "source": c,
            "target": d
        }
    ]
}

如果有人可以帮助我使用javascript解决此问题,那就太好了。

4 个答案:

答案 0 :(得分:2)

首先创建一个具有节点ID的集合

<div class="leftInfoBox">
        <ol>
          <li><a href="#">One</a></li>
          <li><a href="#">Two</a></li>
          <li><a href="#">Three</a></li>
          <li><a href="#">Four</a></li>
        </ol>
      </div>

然后按如下所示过滤链接数组:

const ids = nodes.map(node => node.id);
const idSet = new Set(ids);

那么响应将是

const filteredLinks = links.filter(link => idSet.has(link.target) && idSet.has(link.source))

答案 1 :(得分:1)

reduce方法可以为您做到这一点:

let nodes = [{
      "id": 'b',
      "year": 3
   },
   {
      "id": 'c',
      "year": 1
   },
         {
      "id": 'd',
      "year": 2
   }
];
let links = [
   {
      "source": 'a',
      "target": 'b'
   },
   {
      "source": 'a',
      "target": 'c'
   },
   {
      "source": 'b',
      "target": 'a'
   },
   {
      "source": 'c',
      "target": 'd'
   }
];


const filteredLinks = links.reduce((p,c,i) => {
   if(
      nodes.some(x => x.id===c.source) 
      && 
      nodes.some(x => x.id===c.target)
   )
   {
      p.push(c) 
   }; 
   return p  
},[]);

console.log(filteredLinks)

答案 2 :(得分:0)

links.filter((link)=>{
    let sourceMatch = nodes.find((node)=>{
        return node.id == link.source;
    });

    let targetMatch = nodes.find((node)=>{
        return node.id == link.target;
    });

    return sourceMatch && targetMatch;
});

答案 3 :(得分:0)

另一种使用双重if (start > 0 && start != L) //start is 0 so this won't enter else if (start == L) //start is 0 so this won't enter else if (start < 0 && start > L) //start is 0 so this won't enter forEach的方法。

splice

相关问题