Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda