brunodd brunodd - 2 months ago 11
Javascript Question

Log specific property value from object

I have this object:

choices: {'Frederico' : true, 'Roberto' : false, 'Carlos' : false}


and I am trying to log only the property that has a true value

for(var keyProperty in choices) {
if(choices.hasOwnProperty(keyProperty)) {
console.log(choices[keyProperty]);
}
}


But I am getting all properly values logged. How I can log the property keys that has the
true
value?

Answer

Check for true:

for(var keyProperty in choices) {
    if(choices.hasOwnProperty(keyProperty) && choices[keyProperty] === true) {
      console.log(choices[keyProperty]);
    }
}