get last element of a json object in javascript
var highest = json[ Object.keys(json).sort().pop() ];
Object.keys
(ES5, shimmable) returns an array of the object's keys. We then sort them and grab the last one.
You can't ensure order in a for..in
loop, so we can't completely rely on that. But as you said the keys are in ascending order, we can simply sort them.
Try this:
var lastKey;
var json = {"20121207":"13", "20121211":"9", "20121213":"7", "20121219":"4"};
for(var key in json){
if(json.hasOwnProperty(key)){
lastKey = key;
}
}
alert(lastKey + ': ' + json[lastKey]);