Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda