Elevate the elegance of your switch statement

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);
    });

Answer №1

If you want to simplify the process, consider storing both the inputs and outputs in an object. This way, you can easily retrieve the desired output by referencing the object.

// Organize input-output pairs in an object
let regions = {
  France: "paris",
  Spain: "madrid",
  Germany: "berlin",
  Italy: "rome"
};

let selectedRegion = $('#European_Countries option:selected').text();

// Load the relevant document by constructing a string based on the object lookup
$('#european_cities').load(regions[selectedRegion] + '-cities.html');

$('#european_cities').change(function () {
   let citySelected = $(this).val();
   let status = 'OK';
   fetchData(citySelected);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is my approach to gradually unveiling a 3D object in Three.js correct?

I'm eager to craft a dynamic 3D line chart using three.js that emerges from left to right, similar to the demonstration on CNBC found here: http://youtu.be/ds7zhCqlrqk?t=12s Initially, I explored options like hiding, masking, or clipping segments of ...

Can you suggest a more "ember-esque" approach to calculate this value?

Note: Due to my current situation, I must work with Ember 2.18 but I am curious if version ^3.4 has certain features that 2.x does not. I am creating a Boolean based on the values of two other Booleans. Within the class, the following code snippet is pres ...

Spontaneously fluctuate image transparency

I'm in need of some assistance with an issue I'm facing. I have 5 images positioned using Bootstrap and I want to add a fade animation to them on page load. Below is the code snippet I've been using, which works fine, but I would like the im ...

Utilizing AJAX to seamlessly transfer id elements to a database

I have the following working code: <script> function displayUserData(str) { if (str=="") { document.getElementById("userDetails").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLH ...

Creating an image slideshow with a looping JavaScript array: Step-by-step guide

One issue with the program is that when it runs, only the last array value image is displaying on the screen while the other images are not. Below is the HTML code: <img id="mg" alt="image not found"> And here is the JavaScript code: var images=[ ...

Compiling TypeScript into JavaScript with AngularJS 2.0

Exploring the capabilities of AngularJS 2.0 in my own version of Reddit, I've put together a script called app.ts ///<reference path="typings/angular2/angular2.d.ts" /> import { Component, View, bootstrap, } from "angular2/angular2 ...

GM Unable to Establish Cross-Domain Ajax Connection

Attempting to populate a form on a client's website with data from our database using a Greasemonkey script, but struggling with the same origin policy. I have tried using GM_xmlhttpRequest and even specified @grant GM_xmlhttpRequest but without succ ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

The JSON file is not filling the options in the dropdown menu

procedure Add the objects from the dropdown into the dropdown menu. The Json file is located in root/ajax/.json and the working file is stored in root/.html. Problem: None of the objects from the JSON file are appearing in the dropdown menu. I attempted ...

"Utilizing jQuery's AJAX POST method with PHP is successful, while using XMLHttpRequest is not yielding

Currently in the process of revamping my existing code to transition from jQuery's AJAX function to using XMLHttpRequest in vanilla JS. My understanding is that the following code snippets should be equivalent. However, while the jQuery version functi ...

"Looking to log in with NextAuth's Google Login but can't find the Client Secret

I am attempting to create a login feature using Next Auth. All the necessary access data has been provided in a .env.local file. Below are the details: GOOGLE_CLIENT_ID=[this information should remain private].apps.googleusercontent.com GOOGLE_CLIENT_SECR ...

Error: Unable to access the property 'existsSync' since it is undefined - Creating Web Applications using Node.js and Express.js by Ethan Brown - Chapter 13

I am brand new to GitHub and the MEAN (mongodb, express, angular, node.js) stack. I am currently working through a book by Ethan Brown called 'Web Development with Node and Express', and he has provided a Git repository for me to clone and follow ...

How can I integrate vue-cli output into a PHP project?

One benefit of using vue-cli is that it automatically sets up a local server for you. I'm curious, can I utilize the output from vue-cli in a PHP project (such as app.js )? Another question I have is related to the local network - How does it suppo ...

$injector.modulerr problem

After spending a considerable amount of time analyzing every line of code, I can't seem to pinpoint any errors. Here is what I have: HTML: <body ng-app='myApp'> <div class="wrapper"> <nav> <ul ng-controller="pat ...

Integrating image transitions into JavaScript

Could you provide guidance on how to create buttons from the three images within the "fadein" div in order to navigate directly to a specific jpeg? Currently, the three jpgs are displayed in a continuous loop. Thank you. ...

Resolving the Smooth Scrolling Problem

Here is a simplified version of what I am currently working on: Although I have managed to get the scrolling functionality to work, there seems to be an issue with transitioning from one section to another. For example, when clicking on NUMBER 3, it s ...

Encountered a TypeError: The function _this.settings is not defined - Dealing with integration of barba.js and three.js

I'm currently working on a website that utilizes barba.js. Within the "slider" page, there is a three.js scene integrated. Initially, when I open the page everything functions as expected. However, if I navigate from the slider page to the home page a ...

How can I access and modify objects within a state array in reactJS when using the setState() method?

Upon reviewing my code, I came across the following declaration: constructor(props) { super(props); this.state = { productArray: [{ barcode: '', name: '' }], numberOfRecords: ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...