How do I find the last element in a JavaScript object, if by “last” I consider the one with the largest index? I.e. I am receiving an object similar to an array over ajax (as json), but it also has a non-numeric key:
var received = {
0: 'something',
1: 'something else',
2: 'some stuff',
3: 'some more stuff',
'crap' : 'this screws the whole thing'
}
If it were a plain array, I would use array.length. Similarly, I can simply iterate element by element to find it.
Is there a better way? If jQuery is needed for the solution, that’s also fine.
This works like the codes from zzzzBov and David Müller, but uses library functions do make it much shorter:
If you have objects with enumerably-extended prototype objects (which is not the case for
JSON.parseresults) you might want to useObject.getOwnPropertyNamesinstead.