Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know you're at the last pass of a for loop through object?

Tags:

javascript

I have an object like so:

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

I am now looping through this object and searching for the object keys that are true, like so:

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

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

like image 538
Squrler Avatar asked Oct 31 '22 21:10

Squrler


1 Answers

You can count the object elements with Object.keys(obj).length, and then checks inside the loop to find when you're working with the last one.

The Object.keys(obj) method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

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 could make your own custom function or go ahead with polifill...
Read more about this in this related question.

like image 59
gmo Avatar answered Nov 12 '22 14:11

gmo