getting the last item in a javascript object

No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrot and at other times be banana and so on. If you need to rely on ordering, your best bet is to go with arrays. The power of key-value data structures lies in accessing values by their keys, not in being able to get the nth item of the object.


last = Object.keys(obj)[Object.keys(obj).length-1];

where obj is your object


Yes, there is a way using Object.keys(obj). It is explained in this page:

var fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
Object.keys(fruitObject); // this returns all properties in an array ["a", "b", "c"]

If you want to get the value of the last object, you could do this:

fruitObject[Object.keys(fruitObject)[Object.keys(fruitObject).length - 1]] // "carrot"