Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
689 views
Welcome To Ask or Share your Answers For Others

1 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...