Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

312
Views
JS Is it possible to use switch case in all values of an array automatically?

I want to to use a switch case to an array that has an uncertain number of elements, so there must to be a case to each value of this array; something like this:

let cities = ["City A", "City B", "City C"];

switch (cities){
    case cities[0]: //Action
    break;
    case cities[1]: //Action
    break;
    case cities[2]: //Action
    break;
}

But it cannot be written manually, it has to work like a "for"; something like this:

switch (cities){
    for(let i = 0; i < cities.length; i++){
         case cities[i]: //Action
         break;
    }
}

But JavaScript doesn't allow me to do this.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Need more context, but if I understand you correctly there is classical way to handle cases like this.

It is better to create mapping.

const map = {
  "City A": () => { // action }, 
  "City B": () => { // action }, 
  "City C": () => { // action }
};

const city = 'City A';
map[city]();
over 4 years ago · Santiago Trujillo Report

0

You can not define that, and also if you could, what would you put inside that switch case? If you can generalize it, you don't need switch case, if each action is specific for each item, then you can't use for. What you can do, is to store the action as a member of the map and call it based on the data:

const map = {
  "City A": {
      action: () => { // action specific to City A }
  } 
  "City B": {
      action: () => { // action specific to City B }
  }, 
  "City C": {
      action: () => { // action specific to City C }
  } 
};

Then you would be able to call it dynamically:

map['City A'].action();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!