admin管理员组

文章数量:1129219

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

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

Share Improve this question edited Jan 25, 2024 at 13:44 isherwood 61k16 gold badges120 silver badges168 bronze badges asked Nov 30, 2010 at 19:05 sprugmansprugman 19.8k36 gold badges115 silver badges164 bronze badges 5
  • 1 That's a good question. Also, how can objects be checked for emptyness, other than looping over them? – Lukas Eder Commented Nov 30, 2010 at 19:15
  • 2 property not "item". and no, property order is undefined. – Free Consulting Commented Nov 30, 2010 at 19:15
  • the last property value he means, I would say – KooiInc Commented Nov 30, 2010 at 19:26
  • Do object consider as an ordered data structure? – Salitha Commented Nov 16, 2021 at 16:44
  • How are you defining "last item"? Properties don't generally have an intrinsic order. – Suncat2000 Commented Apr 29, 2022 at 17:19
Add a comment  | 

16 Answers 16

Reset to default 282

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.

last = Object.keys(obj)[Object.keys(obj).length-1];

where obj is your object

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()]
var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";

source:http://javascriptweblog.wordpress.com

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"

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]);

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.

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

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

Or something like

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

Or even..

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

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

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'

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

Object.values(fruitObject)[Object.values(fruitObject).length - 1]; // "carrot"

Edit

To improve performance, you could create a variable:

const fruitValues = Object.values(fruitObject);

To give you:

fruitValues[fruitValues.length - 1];

const fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
const lastValue = Object.values(fruitObject).slice(-1)[0];

It seems to be a short way.

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/values https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

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

Let obj be your object. Exec:

(_ => _[Object.keys(_).pop()])( obj )

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'
 const obj = { a: 'apple', b: 'banana', c: 'carrot' };
    
    // Get the last value using slice
    const values = Object.values(obj);
    const lastValue = values.slice(-1)[0];
    
    console.log(`Last value: ${lastValue}`);
    // Last value: carrot

本文标签: How can I get the last item in a JavaScript objectStack Overflow