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!
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)
Once you figure out whether you have a real JavaScript object or if you have to parse a JSON into a object first, your case needs to include the entire object to work.
It would look like this:
const obj = { a: "value_a", b: "value_b" };
switch (obj) {
case { a: "value_a", b: "value_b" }:
// insert your code here
break;
default:
case { a: "value_a2", b: "value_b3" }:
// insert your code here
break;
}
As long as your case matches the entire object, it will work fine. Or you could make one to match a single property, which in that case would look like:
switch (obj.a) {
case "value_a":
// insert your code here
break;
default:
case "value_a2":
// insert your code here
break;
}
isEqual("{'a': val_a,'b': val_b}", {'x','y'})...? :/{ a: val_a, b: val_b }is a JavaScript object.{ 'a': val_a, 'b': val_b }is a JSON object. You would either need this parsed if it is indeed JSON withJSON.parse(obj)or figure out what's going on your side before attempting a switch case.