从对象数组中导出唯一 属性 值的数组

derive array of unique property values from an array of objects

所以,我从 d3

得到了一个 link 对象数组
nodelinks
(6) […]
0: Object { index: 1, source: {…}, target: {…} }
1: Object { index: 5, source: {…}, target: {…} }
2: Object { index: 8, source: {…}, target: {…} }
3: Object { index: 9, source: {…}, target: {…} }
4: Object { index: 10, source: {…}, target: {…} }
5: Object { index: 21, source: {…}, target: {…} }
length: 6
<prototype>: Array []

我想从中派生一个包含唯一节点的新数组,包括 sourcetarget。我设法这样做了:

_nodes = []
nodelinks.forEach(x => {
  if (!(x.target in _nodes)){_nodes.push(x.target)};
  if (!(x.source in _nodes)){_nodes.push(x.source)};
});

new Set(_nodes).forEach(x => d3.select(`#${x.id}`).classed('active', true))

但真的!一定有更好的方法:一些聪明的 javascripty 习语 map()filter() 或其他东西,是吗?或者也许 d3 有一些本机数组方法?在 python 中,我会使用列表理解。我一定遗漏了一些明显的东西。

有什么提示吗?

哈!我知道我遗漏了一些明显的东西:Array().flat() 非常 有用:而不是遍历对象数组 nodelinks 和推送到一个新数组,我可以像这样使用 map():

new Set(nodelinks.map(x => [x.source, x.target]).flat())

抱歉打扰了,但也许我天真无邪的胡言乱语对你有所启发。