问题
how can I check if all the keys in a json object equal to true? my object looks like this
success = {
"first_name": false,
"middle_name": false,
"last_name": false,
"d_o_b": false,
"sex": false,
"email": false,
"re_email": false,
"password": false,
"re_password": false
};
I proccess the object and every thing that turns out ok gets changed to true, now at the end I want to check if all are true, how can I do this? thank's :-)
回答1:
Or a bit more functionally:
Object.keys(success).every(function(key) {
return success[key];
});
回答2:
var everythingOK = true;
for (var i = 0; i < success.length; i++)
{
if( ! success[i])
{
everythingOK = false;
break;
}
}
if(everythingOK)
alert('Success!');
this should do ;)
回答3:
The most straightforward way is with a for
loop. This will ensure it will work with older browsers that may not support iterators.
var all_true = true;
for (var s in success) {
if (!success[s]) {
all_true = false;
break;
}
}
The break
is not strictly necessary but will short-circuit the loop if all you care about if that none are false.
来源:https://stackoverflow.com/questions/17752137/how-to-check-if-all-keys-in-json-equal-true