var obj = { \'a\' : \'apple\', \'b\' : \'banana\', \'c\' : \'carrot\' }
If I do a
for(key in obj) {
console.log( key + \' has a value
You could loop through all of them and save the last one in a variable.
var lastItem = null;
for(key in obj) {
console.log( key + ' has a value ' + obj[key] );
lastItem = key;
}
// now the last iteration's key is in lastItem
console.log('the last key ' + lastItem + ' has a value ' + obj[lastItem]);
Also, because of how JavaScript works the key is also in your loop's key variable, so the extra variable is not even needed.
for(key in obj) {
console.log( key + ' has a value ' + obj[key] );
}
// now the last iteration's key is in key
console.log('the last key ' + key + ' has a value ' + obj[key]);