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

95
Views
Alternatives to a large if/switch with multiple cases in JavaScript?

I have multiple if statements (50/60) inside a loop.What would be the best approach to perform this actions, switch or map lookup? How can i implement map lockups for the following examples?

errors.forEach((e) => {
      if (e.field === 'firstName') {
        this.hasErrorFirstName = true;
        this.msgFirstName = e.error;
      }
      if (e.field === 'lastName') {
        this.hasErrorLastName = true;
        this.msgLastName = e.error;
      }
      if (e.field === 'middleName') {
        this.hasErrorMiddleName = true;
        this.msgMiddleName = e.error;
      }
      if (e.field === 'address') {
        this.hasErrorAddress = true;
        this.msgAddress = e.error;
      }
     }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do some thing like below

const obj = {
  firstName: ['hasErrorFirstName', 'msgFirstName'],
  lastName: ['hasErrorLastName', 'msgLastName'],
}

errors.forEach(e => {
  if (Object.keys(obj).includes(e.field)) {
    const [has, msg] = obj[e.field];
    this[has] = true;
    this[msg] = e.error
  }
})
about 4 years ago · Juan Pablo Isaza Report

0

This indicates that data is stored in inefficient way. There may be no need to have separate hasErrorFirstName and msgFirstName keys, because error message can be forced to be truthy and be an indicator that there's an error. And there is no need to have keys that are named differently than respective fields. In this case an array can be mapped to a map of error messages:

Object.fromEntries(errors.map(e => [e.field, e.error]))
about 4 years ago · Juan Pablo Isaza 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!