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'
)?
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.
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.
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.
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"
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.
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