1

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;
      }
     }
user2410266
  • 531
  • 2
  • 8
  • 22

2 Answers2

3

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
  }
})
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • Looks like this is not a best practice to do as in this case also user have to write all the fields manually inside `obj`. – Debug Diva May 04 '22 at 07:05
1

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]))
Estus Flask
  • 206,104
  • 70
  • 425
  • 565