'How in JS write a better function which has many IF conditions based on a value and need to return based on it
I'm trying to find out a better solution to write a function that accesses a JSON OBJ.
The OBJ contains countries and nested data as examples:
{
"us": {
"accessCode": "accesscode.wav",
"noAccessCode": "noAccessCode.wav",
"redirecting": "redirecting.wav",
"thanksForCalling": "thanksForCalling.wav",
"notRegisteredPhone": "notRegisteredPhone.wav",
"noSitePhoneAssigned": "noSitePhoneAssigned.wav",
"noCandidatePhoneNum": "noCandidatePhoneNum.wav",
"noCandidate": "noCandidate.wav",
"errorOccurred": "errorOccurred.wav"
},
"it": {
"accessCode": "accesscode.wav",
"noAccessCode": "noAccessCode.wav",
"redirecting": "redirecting.wav",
"thanksForCalling": "thanksForCalling.wav",
"notRegisteredPhone": "notRegisteredPhone.wav",
"noSitePhoneAssigned": "noSitePhoneAssigned.wav",
"noCandidatePhoneNum": "noCandidatePhoneNum.wav",
"noCandidate": "noCandidate.wav",
"errorOccurred": "errorOccurred.wav"
}
}
The function I built so far needs to return the data of the JSON based on a country passed.
The example is below but with many ifs will become ugly probably and I would like to find a different way of doing it. Just imagine if we would have 100 countries.
const obj = {
"us": {
"accessCode": "accesscode.wav",
"noAccessCode": "noAccessCode.wav",
"redirecting": "redirecting.wav",
"thanksForCalling": "thanksForCalling.wav",
"notRegisteredPhone": "notRegisteredPhone.wav",
"noSitePhoneAssigned": "noSitePhoneAssigned.wav",
"noCandidatePhoneNum": "noCandidatePhoneNum.wav",
"noCandidate": "noCandidate.wav",
"errorOccurred": "errorOccurred.wav"
},
"it": {
"accessCode": "accesscode-it.wav",
"noAccessCode": "noAccessCode-it.wav",
"redirecting": "redirecting-it.wav",
"thanksForCalling": "thanksForCalling-it.wav",
"notRegisteredPhone": "notRegisteredPhone-it.wav",
"noSitePhoneAssigned": "noSitePhoneAssigned-it.wav",
"noCandidatePhoneNum": "noCandidatePhoneNum-it.wav",
"noCandidate": "noCandidate-it.wav",
"errorOccurred": "errorOccurred-it.wav"
}
}
const getAudioByCountry = (country) => {
// Simplified but will have more countries
if (country === 'IT') return obj[country.toLowerCase()];
if (country === 'FR') return obj[country.toLowerCase()];
if (country === 'DK') return obj[country.toLowerCase()];
if (country === 'SV') return obj[country.toLowerCase()];
if (country === 'ES') return obj[country.toLowerCase()];
// Default to english
return obj.us;
};
console.log('With country :::: ', getAudioByCountry('IT'));
console.log('With no country :::: ', getAudioByCountry());
Solution 1:[1]
You could return either the wanted language or the default language
const
getAudioByCountry = country => obj[country.toLowerCase()] || obj.us;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
