I got a json object in JavaScript like:
var json = {"20121207":"13", "20121211":"9", "20121213":"7", "20121219":"4"};
without knowing the name of the last key. (The keys are in ascending order)
How can I read the value (and key) of the last element?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With