I want to check a bunch of variables for falsy values.
Instead of writing a very long if statement, e.g.:
if (!userData.email || !userData.lastName || ! userData.firstName etc...
I wanted to put these values in an array and simply check the array, e.g.:
var detailsConditionsArr = [
userData.firstName,
userData.lastName,
userData.email,
userData.phone,
userData.address,
userData.mailAddress,
]
if (detailsConditionsArr.indexOf(false) === 1) {
console.log("Found a falsy");
}
But the above doesn't work (if statement never fires).
The values could be false
, null
or ''
.
Is there a way to check these from the array?
CodePudding user response:
Ideal use case for Array#some
Check for falsy value in the iteration, if the test succeeds, true
will be returned.
var A = ["Name", ""];
var B = ["Name", "30"];
var C = ["Name", "30", null];
if (A.some(el => !el)) {
console.log("Found a falsy in A");
}
if (B.some(el => !el)) {
console.log("Found a falsy in B");
}
if (C.some(el => !el)) {
console.log("Found a falsy in C");
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use reduce to return a single value from the array like so:
var detailsConditionsArr = [
userData.firstName,
userData.lastName,
userData.email,
userData.phone,
userData.address,
userData.mailAddress,
]
if (detailsConditionsArr.reduce((carry, el)=> el ? carry : true, false)) {
console.log("Found a falsy");
}
CodePudding user response:
You can use every
method with Boolean
.
var detailsConditionsArr = [
"test",
12,
"s",
null,
"s",
"test",
]
if (!detailsConditionsArr.every(Boolean)) {
console.log("Found a falsy");
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use the key names you want to check as an array, then do the check like this:
const hasFalsy = ['email', 'lastName', 'firstName'].some(k => !Boolean(userData[k]));
if (hasFalsy) {
console.log('found a falsy');
}
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>