【问题标题】:D3: Merge JSON object entriesD3:合并 JSON 对象条目
【发布时间】:2014-11-20 23:10:59
【问题描述】:

给定以下 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 函数是否已经可以解决这个问题。

感谢您的帮助。

【问题讨论】:

标签: javascript json d3.js merge rollup


【解决方案1】:

处理此问题的一种方法是使用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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-22
    • 2016-03-16
    • 1970-01-01
    • 2019-04-05
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多