Home > Back-end >  Angular typescript switch case by some values
Angular typescript switch case by some values

Time:03-15

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!

CodePudding user response:

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;
}

CodePudding user response:

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)

  • Related