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?
OR
Try this:
Object keys are typically unordered, but looking at the keyset you are using, I made the assumption that you are looking for the highest date in the json keys:
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.If you don't need to support old JS engines:
Don't assume the keys are in order. Get the keys, and then sort them, and then grab that largest value after the sort.
ECMCA script specifications (javascript specifications) do not require browsers to maintain order of the properties of an object.
Related to for-in this is what ECMCA 5 specs say:
Related to the Object.keys method:
It does not make sense to say get the last defined property. You can sort the properties based on the name and get the last one, but if what you want is order then keep an array.