给出以下JSON对象。
{"links":[
{"source": 0, "target": 3, "value": 5},
{"source": 0, "target": 2, "value": 3},
{"source": 0, "target": 2, "value": 3},
{"source": 0, "target": 1, "value": 2},
{"source": 0, "target": 6, "value": 1},
{"source": 0, "target": 6, "value": 1},
{"source": 0, "target": 6, "value": 1},
{"source": 1, "target": 3, "value": 2}
]}
我想对条目进行分组,使源目标对的值相加,像这样。
{"links":[
{"source": 0, "target": 3, "value": 5},
{"source": 0, "target": 2, "value": 6},
{"source": 0, "target": 1, "value": 2},
{"source": 0, "target": 6, "value": 3},
{"source": 1, "target": 3, "value": 2}
]}
有什么方法可以用D3来实现吗?我已经尝试过使用rollup(),但我不知道如何定义一个由多个键(源,目标)组成的键。
我想我可以用下面的答案来解决这个问题 疑问 通过使用for循环和数组操作,但我很想知道是否有一个D3函数可以处理这个问题。
谢谢你的帮助。
处理这个问题的一种方法是用 D3.nest()
:
var nest = d3.nest()
.key(function(d) { return "" + d.source + d.target; })
.rollup(function(leaves) {
var sum = d3.sum(leaves, function(g) { return g.value; });
return {
source: leaves[0].source,
target: leaves[0].target,
value: sum
};
});
然后,在链接数组上使用该嵌套。
data.links = d3.values(nest.map(data.links));
这里有一个工作实例: http:/jsfiddle.netqAHC2830