Javascript按月对json对象进行分组

时间:2014-06-17 10:43:10

标签: javascript json date

我有json object,其中包含日期条目。在下面的json对象中,"timestamp"键下有日期条目。我想在respective month下添加这些日期条目。对于exp。如果有三月份的日期,那么我想在March month下添加所有条目。

[{
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"Success",
  "refID":"6884d5d7-124b-4ab6-83b4-a61c95a16512",
  "errorMessage":null,
  "timestamp":"2014-03-13"
 },
 {
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"failure",
  "refID":"e6c3fc16-15d3-461d-bab2-c3a6ea457a4a",
  "errorMessage":null,
  "timestamp":"2014-03-13"
 },
 {
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"Success",
  "refID":"1c0c6735-f8ed-415a-a39b-1aca466ffdf0",
  "errorMessage":null,
  "timestamp":"2014-03-13"
 },
 {
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"failure",
  "refID":"71a7d08a-a978-4b98-bb14-5f907f0f9135",
  "errorMessage":null,
  "timestamp":"2014-03-13"
}],

2 个答案:

答案 0 :(得分:2)

迭代对象,得到月份,追加到那个月的列表。

注意:按月分组 - 2014年6月将与2013年6月属于同一组。

function group_by_month(data) {
    var months = {}
    for (var i=0; i<data.length; i++) {
       var obj = data[i];
       var date = new Date(obj.timestamp);
       var month = date.getMonth();
       if (months[month]) {
           months[month].push(obj);  // already have a list- append to it
       }
       else {
           months[month] = [obj]; // no list for this month yet - create a new one
       }
    }
    return months;
 }


 result = group_by_month(data);
 console.log("Items of January are ", result[0])
 console.log("Items of February are ", result[1])

答案 1 :(得分:0)

myArray.sort(function(a, b) {
    return new Date(b.timestamp) - new Date(a.timestamp);
});

使用数组过滤器获取每个游行:

var marchArray = myArray.filter(function(o){
  var myDate = new Date(o.timestamp);
  return myDate.getMonth() === 2; // getDate is zero based
})