Elliott Rhys
Elliott Rhys

Reputation: 289

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):
        ...
}

Upvotes: 12

Views: 20507

Answers (2)

walkeros
walkeros

Reputation: 4942

This can be done by first converting the object into json (using JSON.stringify()) and than testing against the json representation. Just make sure that you don't include any extra spaces as this needs to be strictly the same json (best to grab the value by inspecting console.log(JSON.stringify(data))).

This would be something like:

           switch (JSON.stringify(data)) {
                case '{"message":"your message","anotherPropety":"another value"}' : {
                   // your logic             
                   break;
                }
                default: {
                    // your logic
                }
            }

Upvotes: 0

Andrii Muzalevskyi
Andrii Muzalevskyi

Reputation: 3329

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

Upvotes: 23

Related Questions