Reputation: 85
I have the JSON data as below.
[
{
"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}]
And I need to get the data as
[{"avg" : 996.8,"sumcount" :19 , "timestamp":1449360000 }
{"avg": 986.4, "sumcount" :20 ,"timestamp":1449540000 }]
I tried ( I know the code is not correct, still adding) with nest()
but getting the count=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));
})
And the result is [{"key":"996.8","values":0},{"key":"986.4","values":0}]
Upvotes: 0
Views: 793
Reputation: 386883
In plain Javascript you can use Array.prototype.map()
and Array.prototype.reduce()
for collecting count and mapping the objects.
var data = [{ "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 }],
result = data.map(function (a) {
return {
avg: a.avg,
sumcount: a.sessions.reduce(function (s, b) { return s + b.count; }, 0),
timestamp: a.timestamp
};
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Upvotes: 1