2014-09-26 82 views
0

鑑於以下JSON對象:D3:合併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循環和數組操作來處理這個question的答案,但是我很樂意知道D3函數是否已經可以處理這個問題。

感謝您的任何幫助。處理這種

+0

參見:HTTP:/ /bl.ocks.org/phoebebright/raw/3176159/ – 2014-09-26 03:28:07

回答

2

一種方法是用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/

+0

非常好,謝謝! – fhernand 2014-09-26 08:55:19