gpt4 book ai didi

javascript - 使用 Underscore.js 对 Jquery 中的 JSON 数据进行分组

转载 作者:行者123 更新时间:2023-11-28 00:25:35 26 4
gpt4 key购买 nike

我想格式化我的 JSON 数据以在我的报告模板中显示图表。我想生成包含日期明智的已批准、已拒绝和待处理数据的每日报告图表。我当前的 JSON 是:

json_data = '[
{"Approved":1,"updated_date":"2015-03-07"},
{"Approved":1,"updated_date":"2015-03-07"},
{"Rejected":1,"updated_date":"2015-03-07"},
{"Pending":1,"updated_date":"2015-03-07"},{"Approved":1,"updated_date":"2015-03-07"}
]';

我想实现这个输出

$data=  '[
{
"date": "1 Mar",
"approved": 0,
"completed": 0,
"rejected": 0
},
{
"date": "2 Mar",
"approved": 0,
"completed": 0,
"rejected": 0
},
{
"date": "3 Mar",
"approved": 9,
"completed": 20,
"rejected": 11
},
{
"date": "4 Mar",
"approved": 20,
"completed": 50,
"rejected": 30
},
{
"date": "5 Mar",
"approved": 40,
"completed": 50,
"rejected": 10
},
{
"date": "6 Mar",
"approved": 35,
"completed": 70,
"rejected": 20
},
{
"date": "7 Mar",
"approved": 50,
"completed": 80,
"rejected": 30
}];'

我只想通过CHART显示最近7天的数据报告。

最佳答案

您应该首先按“updated_date”过滤初始数据(当日期包含最近 7 天时),然后按“updated_date”分组,然后按组聚合所有所需属性。使用下划线,看起来像这样:

var json_data = '[{"Approved":1,"updated_date":"2015-03-07"}, {"Approved":1,"updated_date":"2015-03-07"}, {"Rejected":1,"updated_date":"2015-03-07"}, {"Pending":1,"updated_date":"2015-03-07"}, {"Approved":1,"updated_date":"2015-03-07"}, {"Approved":1, "Rejected": 1, "updated_date":"2015-03-08"}, {"Pending":17,"updated_date":"2015-03-02"} ]';

var json = JSON.parse(json_data);
var today = new Date('2015-03-10'); // new Date();
var sevenDays = 7 * 24 * 60 * 60 * 1000;

var result = _.map(_.groupBy(_.filter(json, function (item) {
var dateDiff = today.getTime() - new Date(item.updated_date).getTime();
return (dateDiff >= 0 && dateDiff < sevenDays);
}), 'updated_date'), function (g, key) {
var res = _.reduce(g, function (memo, item) {
return {
approved: memo.approved + (item.Approved | 0),
completed: memo.completed + (item.Completed | 0),
rejected: memo.rejected + (item.Rejected | 0),
pending: memo.pending + (item.Pending | 0),
};
}, { approved: 0, completed: 0, rejected: 0, pending: 0 });

res.date = key;

return res;
});

这是一个Live demo in JsFiddle

为了可读性,请使用旧的 for 循环。

附注如果您在客户端执行此操作,请注意 JavaScript 日期和时区。

关于javascript - 使用 Underscore.js 对 Jquery 中的 JSON 数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531453/

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