Home > Enterprise >  Alternatives to a large if/switch with multiple cases in JavaScript?
Alternatives to a large if/switch with multiple cases in JavaScript?

Time:05-04

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

CodePudding user response:

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

CodePudding user response:

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]))
  • Related