0

I have a json object which has a date entries. In the below json object there is date entries under "timestamp" key. I am trying to add those date entries under respective month. For exp. if there is dates from March month then I want add these all entries under 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"
}],
Milind Rasal
  • 19
  • 2
  • 6
  • possible duplicate of [jQuery: Sorting JSON by properties](http://stackoverflow.com/questions/881510/jquery-sorting-json-by-properties) – Liam Jun 17 '14 at 10:49
  • Basically I want show the data throw Graph so it's not only showing data in table or a div. I want to show all entries under respective month and then will get count of entries of for that month. – Milind Rasal Jun 17 '14 at 11:05

2 Answers2

3

Iterate over the objects, get the month, append to list of that month.

Note: grouped by month - June 2014 will be in the same group as June 2013.

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])
Iftah
  • 9,512
  • 2
  • 33
  • 45
  • result[0] is always list of items in January - (or undefined in case no such items). I use Date.getMonth() as the index - it returns 0 only for Janurary – Iftah Jun 17 '14 at 12:35
0
myArray.sort(function(a, b) {
    return new Date(b.timestamp) - new Date(a.timestamp);
});

And to get each march, using array filter :

var marchArray = myArray.filter(function(o){
  var myDate = new Date(o.timestamp);
  return myDate.getMonth() === 2; // getDate is zero based
})
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311