我收集了一些json数据。我希望用d3js完成对这些数据的操作如下:
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"}
];
我根据(http://learnjsdata.com/group_data.html)尝试了以下脚本:
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);
但结果是:
{"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}}
而不是(预期结果):已编辑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
}
]
}
]
我希望你能帮我解决这个问题。
曼尼谢谢
埃里克
答案 0 :(得分:2)
使用Array#forEach
和帮助对象的简单Javascript中的提案。
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>');
&#13;