javascript - D3 : Merge JSON object entries

标签 javascript json d3.js merge rollup

给定以下 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/

相关文章:

javascript - 使用 Jade 作为 angular2 模板引擎

javascript - 将 js 从文件系统加载到 spring boot jar 应用程序中(使用 thymeleaf)

json - 使用 ASP Xtreme Evolution 在经典 ASP 中解析 JSon

javascript - 我怎样才能制作这样的情节?

javascript - 外部 JavaScript 文件在 Rails 中不起作用

javascript - 获取悬停的背景图像

javascript - Backbone.js 路由器具有多页面应用程序?

java - 无参数构造函数是否应该在 jaxb 的上下文中初始化字段?

javascript - 将点添加到 D3 图表

svg - 在D3强制有向图中的链接上添加文本/标签