简体   繁体   中英

How to check if all keys in json equal true

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 :-)

Or a bit more functionally:

Object.keys(success).every(function(key) {
  return success[key];
});

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.

var everythingOK = true;

for (var i = 0; i < success.length; i++)
{
    if( ! success[i])
    {
         everythingOK = false;
         break;
    }
} 


if(everythingOK) 
    alert('Success!');

this should do ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM