mercredi 3 janvier 2018

Simplifying if else statements

Hi I have a json data as below:

{
    "details":
        {
            "data1": 
                {
                    "monthToDate":1000,                   
                    "firstLastMonth":"December",
                    "firstLastMonthAmount":5000,
                    "secondLastMonth":"November",
                    "secondLastMonthAmount":12000
                },
            "data2":
                {
                    "monthToDate":4000,                   
                    "firstLastMonth":"December",
                    "firstLastMonthAmount":10000,
                    "secondLastMonth":"November",
                    "secondLastMonthAmount":15000
                },
           "data3":
                {
                    "monthToDate":2000,                   
                    "firstLastMonth":"December",
                    "firstLastMonthAmount":8000,
                    "secondLastMonth":"November",
                    "secondLastMonthAmount":12000
                }
        }   
}

And I have typescript if statements below,

....
Object.values(data.details.collection).map(obj => {
                if (obj === 'January') {
                    xAxisTranslatedArray.push(this.JAN);
                } else if (obj === 'February') {
                    xAxisTranslatedArray.push(this.FEB);
                } else if (obj === 'March') {
                    xAxisTranslatedArray.push(this.MAR);
                } else if (obj === 'April') {
                    xAxisTranslatedArray.push(this.APR);
                } else if (obj === 'May') {
                    xAxisTranslatedArray.push(this.MAY);
                } else if (obj === 'June') {
                    xAxisTranslatedArray.push(this.JUN);
                } else if (obj === 'July') {
                    xAxisTranslatedArray.push(this.JUL);
                } else if (obj === 'August') {
                    xAxisTranslatedArray.push(this.AUG);
                } else if (obj === 'September') {
                    xAxisTranslatedArray.push(this.SEP);
                } else if (obj === 'October') {
                    xAxisTranslatedArray.push(this.OCT);
                } else if (obj === 'November') {
                    xAxisTranslatedArray.push(this.NOV);
                } else if (obj === 'December') {
                    xAxisTranslatedArray.push(this.DEC);
                }
            });

Am using lodash, highcharts and i18n translations. So each of my this.MONTH is i18n keys. I can't directly pass the values since not able to translate them. So I needed to push to an array each values and pass into highchart's X-axis. My question is basically when I see the if else statements it looks too long and kind of repetitive. Is there any short cut here? Thanks in advance guys.

Aucun commentaire:

Enregistrer un commentaire