简体   繁体   中英

How can I test if all values in an associative array are true? (Javascript)

Associative array:

var signUpStates = {
    "CNPJ": false,
    "PASSWORDS": false,
    "ADDRESS": false,
    "GENERAL_FIELDS": false,
    "TERMS": false,
}

My attempt:

function updateButton() {
    var tempArray = []
    $.each(signUpStates, function(i, val) {
        tempArray.push(val);
    });
    if(tempArray.every(function(e, i, a) { return e == true; })) {
        $(".btn-cadastrar-fornecedor").attr('disabled', false);
    } else {
        $(".btn-cadastrar-fornecedor").attr('disabled', true);
    }
}

Iterating over it and checking individually does not work. What's the best approach to do such a test?

The most straighforward solution (if you are asking about logic) would be to use for loop:

var is = true;

for (var key in signUpStates) {
    if (!signUpStates[key]) {
        is = false;
        break;
    }
}

Strictly saying, correct approach would be also to check only own properties, this is important if the object you are testing might inherit properties from another objects:

var is = true;

for (var key in signUpStates) {
    if (signUpStates.hasOwnProperty(key) && !signUpStates[key]) {
        is = false;
        break;
    }
}

In simple cases like yours, this additional check is not needed.

You can get an array of the object's property names from Object.keys , and then use Array#every :

if (Object.keys(signUpStates).every(function(name) { return signUpStates[name]; })) {
    // All are true
} else {
    // Not all are true
}

With ES2015's (aka ES6) arrow functions, this becomes a bit shorter:

if (Object.keys(signUpStates).every(name => signUpStates[name])) {
    // All are true
} else {
    // Not all are true
}

Support for ES2015 is still relatively thin on the ground, particularly if you have to handle browsers that were released before the spec was finalized, so if this is for a general web page, you'd not use them or use a transpiler. If this is for, say, NodeJS, you can use them directly in v4 and higher.

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