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.data1).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.
Use a separate map object:
const months = {
January: this.JAN,
February: this.FEB,
March: this.MAR,
// etc,
}
Object.values(data.details.data1).forEach(obj => {
if (months[obj]) {
xAxisTranslatedArray.push(months[obj]);
}
});
Alternatively, you can replace the if with a filter:
Object.values(data.details.data1)
.filter(obj => months[obj])
.forEach(obj => xAxisTranslatedArray.push(months[obj]));
Also, note that I'm using forEach instead of map. map is used to modify an array, but you're only iterating over an array. forEach is the semantically correct choice there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With