5

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?

Squrler
  • 3,444
  • 8
  • 41
  • 62

1 Answers1

2

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.

Community
  • 1
  • 1
gmo
  • 8,860
  • 3
  • 40
  • 51