我需要按月通过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/