getting the last item in a javascript object

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

    if you mean get the last key alphabetically, you can (garanteed) :

    var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
    var keys = Object.keys(obj);
    keys.sort();
    var lastkey = keys.pop() // c
    var lastvalue = obj[lastkey] // 'carrot'
    
    0 讨论(0)
  • 2020-12-04 11:43

    You could also use the Object.values() method:

    Object.values(fruitObject)[Object.values(fruitObject).length - 1]; // "carrot"
    
    0 讨论(0)
  • 2020-12-04 11:45

    Map object in JavaScript . This is already about 3 years old now. This map data structure retains the order in which items are inserted. With this retrieving last item will actually result in latest item inserted in the Map

    0 讨论(0)
  • 2020-12-04 11:47
    last = Object.keys(obj)[Object.keys(obj).length-1];
    

    where obj is your object

    0 讨论(0)
  • 2020-12-04 11:47
    JSArray = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };  
    document.write(Object.keys(JSArray)[Object.keys(JSArray).length-1]);// writes 'c'   
    document.write(JSArray[Object.keys(JSArray)[Object.keys(JSArray).length-1]]); // writes 'carrot'
    
    0 讨论(0)
  • 2020-12-04 11:48

    You can try this. This will store last item. Here need to convert obj into array. Then use array pop() function that will return last item from converted array.

    var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
    var last = Object.keys(obj).pop();
    console.log(last);
    console.log(obj[last]);

    0 讨论(0)
提交回复
热议问题