0

我必须按键的值比较 2 个数组。如果“links”数组中的“target”或“source”不是“nodes”数组中的“id”之一,则必须从“links”中删除相应的数组。

从:

{
    "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

4 回答 4

2

首先创建一个包含节点 ID 的集合

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))

那么响应将是

return { nodes, links: filteredLinks }
于 2020-05-19T18:28:59.720 回答
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)

于 2020-05-19T19:15:19.547 回答
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;
});
于 2020-05-19T18:46:26.117 回答
0

另一种使用 doubleforEach和的方法splice

const obj = JSON.parse('{"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"}]}');

obj.nodes.forEach((v,k) => {
obj.links.forEach((q,p) => {
if(v.id !== q.target || v.id !== q.source) {
  obj.links.splice(0,p);
}
});
});
console.log(obj);
;

于 2020-05-19T19:23:13.533 回答