gpt4 book ai didi

javascript - d3 结合键值对对多个值的数据进行分组

转载 作者:行者123 更新时间:2023-11-30 16:06:33 24 4
gpt4 key购买 nike

我收集了一些 json 数据。我想用 d3js 完成的对这些数据的操作如下:

  1. 根据以下 json 键对数据进行分组:“日期”和“姓名”
  2. 统计匹配上述json键的记录
  3. 以键值对的形式返回结果

JSON 数据

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}}

而不是(预期结果):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
}
]
}
]

希望你能帮我解决这个问题。

曼尼谢谢

埃里克

最佳答案

带有 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>');

关于javascript - d3 结合键值对对多个值的数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36958501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com