getting the last item in a javascript object

前端 未结 14 1922
遇见更好的自我
遇见更好的自我 2020-12-04 10:45

If I have an object like:

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

If I don\'t know in advance that the list goes up

相关标签:
14条回答
  • 2020-12-04 11:48

    Use an array, not an object literal, if order matters.

    list = ['apple', 'banana', 'carrot'];
    

    Or something like

    dict = {
     'a' : ['apple', 'awesome'],
     'b' : ['best friend']
    };
    

    Or even..

    dict = [{letter:'a', list:['apple', 'awesome']},{letter:'b', list:['best friend']}];
    

    The keys for dict are not guaranteed at all to be in order.

    0 讨论(0)
  • 2020-12-04 11:50

    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"
    
    0 讨论(0)
提交回复
热议问题