Erik hoeven Erik hoeven - 7 months ago 37
Javascript Question

d3 Grouping data on multiple values in combination with key value pair

I collect some json data. The actions on this data what i want to accomplished with d3js is the following:


  1. Group data on the following json key's: "date" and "name"

  2. Count the records wich match the above json keys

  3. Return the result in a key value pair



JSON DATA

var expenses = [{"name":"jim","amount":34,"date":"11/12/2015"},
{"name":"carl","amount":120.11,"date":"11/12/2015"},
{"name":"jim","amount":45,"date":"12/01/2015"},
{"name":"stacy","amount":12.00,"date":"01/04/2016"},
{"name":"stacy","amount":34.10,"date":"01/04/2016"},
{"name":"stacy","amount":44.80,"date":"01/05/2016"}
];


I tried according the ( http://learnjsdata.com/group_data.html ) the following script:

var expensesTotalByDay = d3.nest()
.key(function(d) { return d.name; })
.key(function(d) { return d.date; })
.rollup(function(v) { return d3.sum(v, function(d) { return d.amount; }); })
.map(expenses);


But this results in:

{"jim":{"11/12/2015":34,"12/01/2015":45},
"carl":{"11/12/2015":120.11},
"stacy":{"01/04/2016":46.1,"01/05/2016":44.8}}


instead of(the expected result): EDITED 21:33

[
{
key: "jim", value:[
{
"key": "11/12/2015",
"value": 34
},
{
"key": "12/01/2015",
"value": 45
}
]
},
{
key: "carl", value:[
{
"key": "11/12/2015",
"value": 120.11
}
]
},
{
key: "stacy", value: [
{
"key": "01/04/2016",
"value": 12
},
{
"key": "01/04/2016",
"value": 34.1
},
{
"key": "01/05/2016",
"value": 44.8
}
]
}


]

I hope you can help me solve this issue.

Manny thanks

Erik

Answer

A proposal in plain Javascript with Array#forEach and a helper object.

var expenses = [{ "name": "jim", "amount": 34, "date": "11/12/2015" }, { "name": "carl", "amount": 120.11, "date": "11/12/2015" }, { "name": "jim", "amount": 45, "date": "12/01/2015" }, { "name": "stacy", "amount": 12.00, "date": "01/04/2016" }, { "name": "stacy", "amount": 34.10, "date": "01/04/2016" }, { "name": "stacy", "amount": 44.80, "date": "01/05/2016" }],
    result = [];

expenses.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { key: a.name, value: [] };
        result.push(this[a.name]);
    }
    this[a.name].value.push({ key: a.date, value: a.amount });
}, Object.create(null));

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Comments