Angularjs如何按月将JSON分组并将其显示在图表中

时间:2018-01-28 19:04:08

标签: javascript angularjs json

我需要几个月通过Angularjs在chart.js中显示来自JSON的数据,但是我的日期是2017-06-12T12:00:00.000Z格式。首先,如果我有这种日期格式,我有问题如何按月份名称(6月,7月,8月等)对数据进行分组。

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轴的总和进行排序。

1 个答案:

答案 0 :(得分:0)

根据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