Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last item in a javascript-value object with a for loop?

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }

If I do a

for (var key in obj) {
  console.log( key + ' has a value ' + obj[key] );
}

It will look through all the values in obj. If I have a much larger object, how do I know if I am on the last iteration of that for loop?

I realize that key value pairs aren't really organized in order, but I need to accomplish something in the very last iteration of this loop and don't know how.

like image 701
Joshua Soileau Avatar asked Jan 12 '14 15:01

Joshua Soileau


People also ask

How do you find the last value of an object?

You can access the last value in an object directly, by using the Object. values() method to get an array of the object's values and calling the pop() method on the result, e.g. Object. values(obj).

How do you find if an key is present in an object JavaScript?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do you remove the last element of an object?

To remove the last element from an array, call the pop() method on the array, e.g. arr. pop() . The pop method removes the last element from the array and returns it. The method mutates the original array, changing its length.


2 Answers

don't use for (key in obj), it will iterate over all enumerable properties including prototype properties, and can lead to amazingly horrible things. Modern JS has a special function for getting only the relevant keys out of an object, using Object.keys(...), so if you use var keys = Object.keys(obj) to get the list of keys as an array, you can then iterate over that:

// blind iteration
Object.keys(obj).forEach(function(key, i) {
  var value = obj[key];
  // do what you need to here, with index i as position information.
  // Note that you cannot break out of this iteration, although you
  // can of course use ".some()" rather than ".forEach()" for that.
});

// indexed iteration
for(var keys = Object.keys(obj), i = 0, end = keys.length; i < end; i++) {
  var key = keys[i], value = obj[key];
  // do what you need to here, with index i as position information,
  // using "break" if you need to cut the iteration short.
});

or select its last element immediately

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

or using a slice:

var keys = Object.keys(obj);
var last = keys.slice(-1)[0];

or using a shift (but that's a destructive operation, so we're not caching the keys because the shift turns it into "not all the keys anymore"):

var last = Object.keys(obj).shift();

2021 edit

There is now also the Object.entries function, which gets you key/value pairs in one go:

Object.entries(obj).forEach(([key, value]) => {
  console.log(`key "${key}" points to:`, value):
});
like image 71
Mike 'Pomax' Kamermans Avatar answered Sep 29 '22 05:09

Mike 'Pomax' Kamermans


You could loop through all of them and save the last one in a variable.

var lastItem = null;
for(var 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(var 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]);
like image 44
PurkkaKoodari Avatar answered Sep 29 '22 07:09

PurkkaKoodari