Reputation: 13
I have simple JavaScript question.
I have an array (xyz) of 9 objects (Cell), each with 2 properties (e,v).
Is there any easy way to check if all the values of one of the properties are false?
Something like:
var myArray = xyz[];
if(all myArray.e==false){
do this;
}
Thanks :D
Array[9]
0:Cell
e:false
v:"x"
1:Cell
2:Cell
3:Cell
4:Cell
...etc
Upvotes: 0
Views: 73
Reputation: 22524
You can use array#every
with to check for your condition to be true for all the objects in your array. Use Object#keys
to iterate over keys in an object and check for false value using array#some
.
var arr = [{e:false, v:'x'}, {e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'}],
result = arr.every(o => Object.keys(o).some(k => !o[k]));
console.log(result);
To check for e
property in your object, you should first check if e
key exists in the object then check if its value is false.
var arr = [{e:false, v:'x'}, {e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'}],
result = arr.every(o => 'e' in o && !o.e);
console.log(result);
Upvotes: 0
Reputation: 1140
You have multiple options to do that, like
But for short answer I think you can use findIndex that will return index if it matches condition: Example :
if(xyz.findIndex(k => k.e== false) > -1){
console.log("it contains false value also");
}
Upvotes: 0
Reputation: 18393
You can use JavaScript Array every() Method
var myArray = [xyz];
if (myArray.every(obj => !obj.e)) {
do this;
}
Upvotes: 1
Reputation: 1
There's a few different ways you could approach this. One way would be by using
every
. (MDN Docs)
function myTest(thisItem) {
return !thisItem.e;
}
var myArray = [
{e: false, v: 111},
{e: false, v: 222},
{e: false, v: 333}
];
var output = myArray.every(myTest);
console.log(output);
// expected output: true
Upvotes: 0
Reputation: 968
You should do
let areAllFalse = true;
for (let obj in myArray){
if (e.v) {
areAllFalse = false;
break;
}
}
if (areAllFalse){
// Do stuff
}
Basically:
areAllFalse
) to true (you are assuming that all the elements will be false)areAllFalse
is true, every element in the array is false, so you can execute your codeThis will work in every programming language (with the obvious syntax changes)
I hope I helped you :)
Upvotes: 0