Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the last item in a javascript object

If I have an object like:

{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' } 

If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot')?

like image 751
sprugman Avatar asked Nov 30 '10 19:11

sprugman


People also ask

How do you find the last object of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do I remove the last key value of a object?

Objects do not have any defined order of properties so there is no "last" property. You have to remove a property by name, not position. You can, of course, iterate over the properties and inspect them as you iterate and decide whether you want to delete any given property by looking at its name.

How do you find the length of an object?

You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.


2 Answers

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" 
like image 97
Kristina Stefanova Avatar answered Sep 22 '22 06:09

Kristina Stefanova


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.

like image 39
Alex Avatar answered Sep 22 '22 06:09

Alex