getting the last item in a javascript object

前端 未结 14 1921
遇见更好的自我
遇见更好的自我 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:24

    Let obj be your object. Exec:

    (_ => _[Object.keys(_).pop()])( obj )
    
    0 讨论(0)
  • 2020-12-04 11:25

    As for the ordering of object properties in Javascript, I will just link to this answer:

    Elements order in a "for (… in …)" loop

    Specifically:

    All modern implementations of ECMAScript iterate through object properties in the order in which they were defined

    So every other answer here is correct, there is no official guaranteed order to object properties. However in practice there is (barring any bugs which naturally can screw up even set-in-stone officially specified behavior).

    Furthermore, the de-facto enumeration order of object properties is likely to be codified in future EMCAScript specs.

    Still, at this time I would not write code around this, mostly because there are no built-in tools to help deal with object property order. You could write your own, but in the end you'd always be looping over each property in an object to determine its position.

    As such the answer to your question is No, there is no way besides looping through an object.

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

    Solution using the destructuring assignment syntax of ES6:

    var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
    var { [Object.keys(temp).pop()]: lastItem } = temp;
    console.info(lastItem); //"carrot"

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

    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.

    0 讨论(0)
  • 2020-12-04 11:37
    var myObj = {a: 1, b: 2, c: 3}, lastProperty;
    for (lastProperty in myObj);
    lastProperty;
    //"c";
    

    source:http://javascriptweblog.wordpress.com

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

    The other answers overcomplicate it for me.

    let animals = {
      a: 'dog',
      b: 'cat',
      c: 'bird'
    }
    
    let lastKey = Object.keys(animals).pop()
    let lastValue = animals[Object.keys(animals).pop()]
    
    0 讨论(0)
提交回复
热议问题