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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With