Reputation: 16234
I have an object in which I have to verify different values using multiple if-else statements, like below is sample javascript snippet:
if(properties.values.a > 0 ){
}else if(properties.values.b > 0){
}else if(properties.values.c > 0){
}else if(properties.values.d > 0){
}else if(properties.values.e > 0){
}else{
}
I am willing to replace this multiple if-else statement into switch-case. Now I wonder if that is possible for objects or not? If possible, how should be going towards it?
Upvotes: 1
Views: 754
Reputation: 59386
In JavaScript you can only use switch
to check for equality. You can't check whether a > b
using a switch.
If you want a more elegant solution, that I particularly would only use if I needed to check a huge amount of rules, is to do something like this:
const checkers = [];
checkers.push([p => p.values.a > 0, () => { /* do something */ }])
checkers.push([p => p.values.b > 0, () => { /* do something */ }])
...
checkers.filter(checker => checker[0](property)).forEach(checker => checker[1]())
In the above example, checkers is an array of arrays in which the first element is a predicate function and the second is a function that should execute if the predicate is true.
But again... For most cases you just do an if/else
as you described.
Also, if you want to check if a value is greater than 0, you might use just if(a)
, because if a
is not 0
, then it's truthy, otherwise it's falsy.
EDIT
Apparently, technically, you can use logical expressions within switch
statements, even though it seems hacky =/
Upvotes: 1
Reputation: 386680
You could use an array with the wanted keys and use iterate with a short circuit if a value is found.
If no one is found call callOther
.
['a', 'b', 'c', 'd', 'e'].some(k => {
if (properties.values[k] > 0) {
callThis();
return true;
}
}) || callOther();
Upvotes: 1
Reputation: 1401
Switch is not supposed to work like this. So, no, this is not supported. As a workaround you could do this
switch (true) {
case (properties.values.a > 0):
...
case (properties.values.b > 0):
...
case (properties.values.c > 0):
...
case (properties.values.d > 0):
...
case (properties.values.e > 0):
...
}
Still, is pretty ugly so i suggest you stick to if/else.
Upvotes: 2
Reputation: 12880
You can do that with a for in
loop:
o = {
a:0,
b:0,
c:1,
d:0
};
for(var p in o) {
if (o[p] > 0) {
//...
console.log(o[p]);
break;
}
}
Upvotes: 1