How do you know that you are on the last pass of a for loop through an object?

I have an object like this:

var obj = { thing_1 : false, thing_2 : false, thing_3 : true, thing_4 : false, thing_5 : true } 

Now I go through this object and look for the key of the object that is true, for example:

  for (value in obj){ if (obj[value] === true ){ // do something } } 

How do I know when I reached the last byte of the loop where one of the keys is true?

+5
source share
1 answer

You can count object elements with Object.keys(obj).length and then check inside the loop to find when you are working with the latter.

The Object.keys (obj) method returns an array of specified objects, which can be listed in the same order as provided by a for ... in loop (the difference is that the for-in loop lists the properties in the prototype chain).

Example:

 var obj = { thing_1: false, thing_2: false, thing_3: true, thing_4: false, thing_5: true }; var count = 0; for (var value in obj) { count++; if (count == Object.keys(obj).length) { console.log('And the last one is:'); } console.log(obj[value]); } 

Note. . As you can imagine, this has some problems with IE < 9 ...
you can create your own function or continue working with polifill ...
More on this in this related question .

+2
source

All Articles