128

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

sprugman
  • 19,351
  • 35
  • 110
  • 163

15 Answers15

281

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"
Benny Code
  • 51,456
  • 28
  • 233
  • 198
Kristina Stefanova
  • 2,835
  • 2
  • 13
  • 3
  • 8
    This one should've been the accepted one, that `Object.keys` works awesome. Just gotta find a way to make it work on IE8 and 7, because that showed up only on IE9. – RaphaelDDL Jul 02 '13 at 20:47
  • I was grouping by date with _.groupBy server side (node). Work like a charm, I don't know why people says there are no guarantee about orders. – Dimitri Kopriwa Jan 29 '15 at 11:11
  • 5
    you could do directly with Object.values(fruitObject) which will return the values instead of the keys,and then do a pop() to your array to return the last element. – Yvon Huynh Aug 29 '16 at 19:29
  • 6
    [The first answer here](https://stackoverflow.com/questions/4317456/getting-the-last-item-in-a-javascript-object#answer-4317488) is the correct answer. I tried using `Object.keys` over and over only to find that the properties were actually ordered randomly. The actual property order is different from what is displayed when logged to your browsers console. When logged to the browser console, properties are automatically reordered and displayed alphabetically/numerically, which definitely causes some confusion. – kennsorr Apr 04 '19 at 14:36
  • 2
    JS spec does not guarantee order of the key and it can vary between different implementations(engines). Hence it's not possible to guarantee the insertion order for randomly generated(keyed) object. The Array is a type of Object where key is numeric index to guarantee the order of insertion among other useful properties. – Ethan Doh Mar 14 '20 at 01:38
  • 2
    Good lord people had a hard time doing web development back in 2010-2013... – Merc Apr 06 '20 at 04:29
  • 1
    You have added Object.Keys 2 times, Do you know How much time it will take to responsd? Instead of it, I have a better solution which use Object.keys just one time. – Rajat Sep 20 '20 at 02:37
  • Nowadays this works too: `fruitObject[Object.keys(fruitObject).at(-1)]` :) – derschiw Jul 05 '23 at 18:09
78

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.

Alex
  • 64,178
  • 48
  • 151
  • 180
  • 2
    As an expansion on this entirely correct answer. Objects are not arrays, even if you create an associative array in JS using the array markers `[]` it is really an object. JS does not have associative arrays as such, arrays have indexed access and sequence; objects have associative property access, non-sequential. – Orbling Nov 30 '10 at 19:11
  • 4
    I know they aren't guaranteed to have an order, but if I have control over the object's creation, in practical terms, I can make sure they're in an specific order. Clearly, the answer to the question, though, is "no". :) – sprugman Nov 30 '10 at 19:31
  • 2
    @sprugman: Not in Chrome. A long a heated debate has been raging about this subject: http://code.google.com/p/v8/issues/detail?id=164 – Tim Down Nov 30 '10 at 23:09
  • 9
    For those folks who cross this page 10yrs on: the answer should be updated. Order of object properties is guaranteed by the standard now. Also, the question wasn't about JSON. – Robert Monfera Jan 31 '21 at 17:43
  • 1
    Even with guaranteed ordering, there is merit to this answer in spirit. With arrays, the idea of "last element" is well-defined. Objects, on the other hand, require iterating all entries in O(n) to get the last element, which loses the benefit of O(1) key-based access, the primary purpose of the data structure. Performance aside, "last element in object" is semantically surprising. This isn't to say you should never use `Object.entries`/`.keys`/`.values` to get the last entry, it's that if you are doing it excessively, you might want to reconsider your data structure choice. – ggorlen May 20 '21 at 22:51
29
last = Object.keys(obj)[Object.keys(obj).length-1];

where obj is your object

krzysiej
  • 889
  • 9
  • 22
user3282891
  • 307
  • 3
  • 2
  • 3
    This gets the last key (`'c'` in this case) but the question is worded in a way that implies the asker is looking for the last value (`'carrot'`). This also doesn't really add anything that isn't already covered by [Kristina Stefanova's answer](https://stackoverflow.com/a/16590272/399105) – bmaupin Jul 31 '17 at 18:45
  • 1
    Store `Object.keys(obj)` in a variable for a ~50% speed increase and more readability (less repetition/line noise). – ggorlen May 21 '21 at 00:15
19

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()]
somebodysomewhere
  • 1,102
  • 1
  • 13
  • 25
  • Your answer is simple and _technically_ could be considered _a_ correct answer for the question that was asked. However, with your code and how objects really operate, the "last" key is not always `'c'` and value `'bird'`. This is due to the definition of and differences in implementations of a JavaScript object. – Suncat2000 Apr 29 '22 at 17:32
15
var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";

source:http://javascriptweblog.wordpress.com

George
  • 159
  • 1
  • 2
10

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"
ollazarev
  • 1,076
  • 8
  • 26
9

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]);
Shapon Pal
  • 1,098
  • 3
  • 16
  • 27
5

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
5

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.

Community
  • 1
  • 1
MooGoo
  • 46,796
  • 4
  • 39
  • 32
  • As you say, I definitely wouldn't rely on any order for object property enumeration. For a start, new ECMAScript implementations are under no obligation to follow this de facto standard, so code relying on a particular order is not future-proof; also, not all current browsers behave the same. See this discussion on the Chrome bug tracker: http://code.google.com/p/v8/issues/detail?id=164. Finally, I wouldn't expect the ECMAScript spec to standardize this any time soon. – Tim Down Nov 30 '10 at 23:11
3
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'
TotPeRo
  • 6,561
  • 4
  • 47
  • 60
Reha Ozenc
  • 39
  • 4
3

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

AshNaz87
  • 376
  • 3
  • 14
  • 1
    Why not save `Object.values(fruitObject)` in a variable and speed the code up by up to 50%, increasing readability in the process? – ggorlen May 21 '21 at 00:12
3
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

grehh
  • 31
  • 2
0

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

vatsa
  • 124
  • 1
  • 9
0

Let obj be your object. Exec:

(_ => _[Object.keys(_).pop()])( obj )
diogo
  • 525
  • 1
  • 7
  • 12
0

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'
Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18