If I have an object like:
{ \'a\' : \'apple\', \'b\' : \'banana\', \'c\' : \'carrot\' }
If I don\'t know in advance that the list goes up
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'
You could also use the Object.values()
method:
Object.values(fruitObject)[Object.values(fruitObject).length - 1]; // "carrot"
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
last = Object.keys(obj)[Object.keys(obj).length-1];
where obj is your object
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 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]);