Sandeep vashisth Sandeep vashisth - 5 months ago 12
JSON Question

Find top 5 property of JSON object in javascript or jquery?

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":""}

Answer

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/