Ericson Willians
Ericson Willians

Reputation: 7845

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?

Upvotes: 2

Views: 766

Answers (2)

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074355

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.

Upvotes: 1

Related Questions