-1

i have a JSON Object like below out of this i want top 5 properties order by date.

var json={"09/03/14":"63.7","09/02/14":"67.4","09/01/14":"67.4","08/29/14":"67.4","08/28/14":"69.4","08/27/14":"69.4","08/26/14":"178","08/25/14":"16.8","08/22/14":""} 
Sandeep vashisth
  • 962
  • 7
  • 19
  • 36

2 Answers2

1

Assuming you want them sorted in ascending date order:

var json = {
    "09/03/14": "63.7",
    "09/02/14": "67.4",
    "09/01/14": "67.4",
    "08/29/14": "67.4",
    "08/28/14": "69.4",
    "08/27/14": "69.4",
    "08/26/14": "178",
    "08/25/14": "16.8",
    "08/22/14": ""
}
var arr = [];
for (d in json) {
    arr.push({
        date: new Date(d),
        d: d,
        v: json[d]
    });
}
arr.sort(function (a, b) {
    if (a.date < b.date) {
        return -1;
    }
    if (a.date > b.date) {
        return 1;
    }
    return 0;
});
json = {};
for (var i = 0; i < 5; i++) {
    json[arr[i].d] = arr[i].v;
}
console.log(json);

To sort in descending order swap the return values from the sort function. Also note that that's not really JSON, it's a javascript object literal.

Fiddle: http://jsfiddle.net/ccjzzfcr/2/

Slippery Pete
  • 2,949
  • 1
  • 10
  • 13
0

DEMO Link

Javascript

var json='{"09/03/14":"63.7","09/02/14":"67.4","09/01/14":"67.4","08/29/14":"67.4","08/28/14":"69.4","08/27/14":"69.4","08/26/14":"178","08/25/14":"16.8","08/22/14":"0"}';
var obj= $.parseJSON(json);
for (var prop in obj) {
    $("#res").append("o." + prop + " = " + obj[prop]+"<br />");
     console.log("o." + prop + " = " + obj[prop]);
}

Update 1:

Sort by date described in this post. Sort object by date

Community
  • 1
  • 1
Hamix
  • 1,275
  • 7
  • 18
  • 2
    The code shown in the question is already an object, not JSON, so no need to parse it. Where's the code sort by date? – nnnnnn Sep 03 '14 at 12:35