Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last element of a JSON object in JavaScript

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?

like image 577
Finwood Avatar asked Jan 03 '13 22:01

Finwood


2 Answers

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.

like image 60
Zirak Avatar answered Sep 21 '22 16:09

Zirak


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]);
like image 22
Danilo Valente Avatar answered Sep 23 '22 16:09

Danilo Valente