After researching alternatives to using a switch statement, I found some interesting methods for simplifying or converting it into an object literal. You can check out these resources for more information:
Rewriting Javascript: Replacing the Switch Statement
Using object literals and map method instead of the old switch statement
However, while attempting to convert the switch statement, I encountered an issue with displaying the correct list of cities based on the selected country. For example, when selecting England, it was showing the cities for Scotland.
Here are two examples of what I tried:
const city = (county) => ({
"England": $('#uk_states').load('england-cities.html'),
"Scotland": $('#uk_states').load('scotland-cities.html'),
//...
})[county]
let county = city([$('#Uk_Cities option:selected').text()]);
let city = {
"England": {
"file": $('#uk_states').load('england-cities.html'),
"label": "england"
},
"Scotland": {
"file": $('#uk_states').load('scotland-cities.html'),
"label": "scotland"
},
//...
let county = city[$('#Uk_Cities option:selected').text()];
let countryCity = `${county.file} ${county.label}`;
I suspect that the problem lies in the way I am handling the conversion from switch statement to the object literal. Could someone please assist me in resolving this issue?
Thank you in advance.
let county = $('#Uk_Cities option:selected').text();
switch (county) {
case 'England':
$('#uk_states').load('england-cities.html');
break;
case 'Scotland':
$('#uk_states').load('scotland-cities.html');
break;
case 'Wales':
$('#uk_states').load('wales-cities.html');
break;
case 'Northern Ireland':
$('#uk_states').load('nireland-cities.html');
break;
default:
}
});
$('#uk_states').change(function () {
let stateSelected = $(this).val();
let responseStatus = 'success';
getTheWeatherData(stateSelected);
});