gpt4 book ai didi

javascript - Angularjs 如何按月份对 JSON 中的日期进行分组并将其显示在图表中

转载 作者:行者123 更新时间:2023-12-03 02:37:25 25 4
gpt4 key购买 nike

我需要通过 Angularjs 在 Chart.js 中按月显示 JSON 数据,但我的日期采用这种格式 2017-06-12T12:00:00.000Z。首先,如果我有这种格式的日期,我会遇到如何按月份名称(六月、七月、八月等)对数据进行分组的问题。

JSON

[
{"id":1,"date":"2017-06-12T12:00:00.000Z.","total":123},
{"id":2,"date":"2017-06-04T12:00:00.000Z.","total":100},
{"id":3,"date":"2017-08-29T12:00:00.000Z.","total":94}
]

其次,如何在 AngularJS 中使用 Chart.js,并在 x 轴上按月份名称排序,在 y 轴上按总计排序日期。

最佳答案

基于an answer to a similar question ,我做了一些更改,以便数组按所需字段的月份和年份进行分组,在本例中为 date .

var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];


var groupByMonth = function(json_data, key_to_group) {
// Iterate over the array
return json_data.reduce(function(array, item) {
// Convert the string into a date to get the month and the year
var item_date = new Date(item[key_to_group]);
// Get the name of the month
var item_month = monthNames[item_date.getMonth()];

// Push the item into the new array
(array[item_month] = array[item_month] || []).push(item);
return array;
}, {});
};


var arr = [
{"id":1,"date":"2017-06-12T12:00:00.000Z","total":123},
{"id":2,"date":"2017-06-04T12:00:00.000Z","total":100},
{"id":3,"date":"2017-08-29T12:00:00.000Z","total":94}
];

// Call the groupByMonth method with the array you want to group, and the name of the field that contains the date
var groupedByMonth = groupByMonth(arr, 'date');
console.log(groupedByMonth);

重要的是要考虑到我编辑了日期时间,以便它们采用正确的格式:我删除了最后的 . 。您还应该考虑到,仅当所有数据都来自同一年时,按月份名称对它们进行分组才有效。

转到问题的第二部分。您所需要的只是一个包含按月总计总和的数组。

// Result after grouping by month
var groupedByMonth =
{
"June": [
{
"id": 1,
"date": "2017-06-12T12:00:00.000Z",
"total": 123
},
{
"id": 2,
"date": "2017-06-04T12:00:00.000Z",
"total": 100
}
],
"August": [
{
"id": 3,
"date": "2017-08-29T12:00:00.000Z",
"total": 94
}
]
};


// Iterate over result
var arr_totals = [];
Object.keys(groupedByMonth).forEach(function (key) {
var month_total = 0;
Object.keys(groupedByMonth[key]).forEach(function (subkey) {
// sum the total of each item of the month
month_total += groupedByMonth[key][subkey].total;
});
// add the total of the month to the array
arr_totals.push(month_total);
});

console.log(arr_totals);

现在您所要做的就是将月份名称作为数组添加到 Y 轴:Object.keys(groupedByMonth) ,总计为 X 轴 arr_totals根据您要创建的图表类型。查看the official Chart.js documentation为此。

关于javascript - Angularjs 如何按月份对 JSON 中的日期进行分组并将其显示在图表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48490230/

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