Reputation: 14419
I'm trying to figure out the best way to interate through a javascript object to see if one of the keys is set to a certain value. I understand I can do a foreach loop but I feel like there is an easier way.
var myObject = {
a: false,
b: false,
c: false,
x: false
}
Id like a quick way to return a true if at least one of those values is set to true, and false if all are false.
Upvotes: 0
Views: 63
Reputation:
var any_true = false;
JSON.stringify(myObject, function(key, value) {
if (value === true) any_true = true;
});
This uses the callback feature of JSON.stringify
. It has the advantage that it finds any true value, even in nested objects.
Upvotes: 0
Reputation: 7336
To return the key
that has yourValue
as its value, just do:
var yourValue = true;
var key = Object.keys(myObject).filter(function (i) {
return myObject[i] === yourValue;
})[0];
It will return undefined
if no key found.
If you dont need the key
and you only need to know if the value is in your object, you can just use the some
method:
var hasValue = Object.keys(myObject).some(function (i) {
return myObject[i] === yourValue;
});
Upvotes: 0
Reputation: 318182
You have to iterate, but you can do something like this
var hasTrue = Object.keys(myObject).some(function(key) {
return myObject[key];
});
this uses Array.some
and stops as soon as a true
value is encountered.
Upvotes: 4