D3的数量总和

时间:2016-01-16 13:11:04

标签: javascript d3.js sum grouping

我有如下的JSON数据。

[

  {
    "avg": 996.8,
    "sessions": [

      {
        "minTime": 0,
        "maxTime": 599,
        "count": 10
      },
      {
        "minTime": 600,
        "maxTime": 1199,
        "count": 2
      },
      {
        "minTime": 1800,
        "maxTime": 2399,
        "count": 4
      },
      {
        "minTime": 2400,
        "maxTime": 2999,
        "count": 3
      }
    ],"timestamp":1449360000},
  {
    "avg": 986.4,
    "sessions": [

      {
        "minTime": 0,
        "maxTime": 599,
        "count": 12
      },
      {
        "minTime": 600,
        "maxTime": 1199,
        "count": 1
      },
      {
        "minTime": 1200,
        "maxTime": 1799,
        "count": 2
      },
      {
        "minTime": 1800,
        "maxTime": 2399,
        "count": 2
      },
      {
        "minTime": 3000,
        "maxTime": 3599,
        "count": 3
      }
    ]
    ,"timestamp":1449540000}]

我需要将数据作为

[{"avg" : 996.8,"sumcount" :19 , "timestamp":1449360000 }
{"avg": 986.4, "sumcount" :20 ,"timestamp":1449540000 }]

我尝试(我知道代码不正确,仍在添加)nest(),但得到的计数= 0

d3.json("Dwell.json", function(error,data){ 

var res = d3.nest()
            .key(function(d) { return d.avg; })
            .rollup(function(v) { return d3.sum(v, function (d) {return d.count})})
            .entries(data);
    console.log(JSON.stringify(res));
})

结果是[{"key":"996.8","values":0},{"key":"986.4","values":0}]

1 个答案:

答案 0 :(得分:1)

在普通的Javascript中,您可以使用Array.prototype.map()Array.prototype.reduce()来收集计数和映射对象。



{{1}}