Search code examples
javascriptjqueryswitch-statementcase-insensitive

Javscript Switch expression - How can it be made case insensitive?


I have two geojson files with the same key/labels but have different cases: feature.properties.STATUS and feature.properties.status

I wish to test both file's label's values with a single switch statement:

    function PathStyle(feature) {
        switch (feature.properties.STATUS) {
            case "FP": 
                return {color: 'blue'}; 
            case "BR": 
                return {color: 'green'};
                etc...
                

This will only produce the expected results for the capitalized STATUS values.

I've tried the .toLowerCase() method in various way, but with no success. ie:

    function PathStyle(feature) {
     var str = "feature.properties.STATUS";
     var strLC = str.toLowerCase();
      console.log(strLC);
        switch (strLC) {
        etc...

Is there a solution to this problem?


Solution

  • Use the null coalescing operator to try both STATUS and status, whichever actually exists.

        function PathStyle(feature) {
            switch (feature.properties.STATUS ?? feature.properties.status) {
                case "FP": 
                    return {color: 'blue'}; 
                case "BR": 
                    return {color: 'green'};
                    etc...