[英]D3: Merge JSON object entries
給定以下 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
};
});
然后,在 links 數組上使用該嵌套:
data.links = d3.values(nest.map(data.links));
這里的工作示例: http : //jsfiddle.net/qAHC2/830/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.