Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check for object properties in a switch statement?

I am trying to process a range of possible responses from an AJAX request and want to do this in a switch statement.

data.message holds the information I'm interested in, however it can be returned as either a string or a JSON object

Testing for a string is simple enough, but I want to know if I can do something like this:

switch (data.message) {
    case 'ok':
        ...
    case 'another string':
        ...
    case (this.id == 123):
        ...
}
like image 893
Elliott Rhys Avatar asked Oct 26 '17 11:10

Elliott Rhys


1 Answers

Simple answer is no, it is not supported,

As a workaround you may try to use following form of switch:

switch (true) {
    case (data.message === 'ok'):
        ...
    case (data.message === 'another string'):
        ...
    case (data.message.id == 123):
        ...
}

This may look better than list of if-else statements

like image 143
Andrii Muzalevskyi Avatar answered Sep 18 '22 11:09

Andrii Muzalevskyi