'Angular typescript switch case by some values

I just try to make a switch by two values.

switch ({'a': val_a,'b': val_b}){
  case ({'x','y'}):
    "some code here"
    break;
}

and this not working... any help? thanks!



Solution 1:[1]

Switch operator only works for primitives, it's not possible to compare objects, but you can create primitive by yourself, e.g string

const compareValue = val_a + ' ' + val_b;

switch (compareValue){
  case 'x y':
    //"some code here"
    break;
}

Solution 2:[2]

The value in a case statement must be a constant or a literal or an expression that evaluates to a constant or a literal. You can't expect a switch statement to have objects and underyling case statements have their own objects and do a comparison.

Having said that you've options in javascript that allow you to transform an object (just for comparison purpose). An approach I would following would be like this

let obj = {'a': 'x','b': 'y'};
let obj1={a:'x',b:'y'};
switch(Object.values(obj).join(','))
{
 case Object.values(obj1).join(','):
   console.log('evaluation succeeds');
 break;
}

So what I've done is took the object values and joined with a comma(effectively having a string), and in the case statement did same with another object (so that comparison could take place)

Solution 3:[3]

switch(true) {
  case obj1.a == obj2.a && obj1.b == obj2.b:
    console.log('true');
    break;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Slawa Eremin
Solution 2 Obaid
Solution 3 flap13