How to check if all keys in json equal true

微笑、不失礼 提交于 2021-01-27 20:31:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!