给定以下 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(),但我不知道如何定义一个由多个键(源、目标)组成的键。
我想我可以找到这个问题的答案 question通过使用 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.net/qAHC2/830/
关于javascript - D3 : Merge JSON object entries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26051108/