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

174
Visualizações
Javascript : skip calling the chaining methods based on a condtion dynamically

I have an array of objects, I call a series of methods on the array. I wanted to skip in between methods based on a condition. Is there a generic way to handle it instead of having an if/else block?

When a filter is applied i wanted to call filter method in this array, when filter is not applied i want skip that.

// when filter is applied
    salesActivityTypes
         .filter(s=>s.selected)
         .map(key => key.name);

//when filter not applied
    salesActivityTypes
         .map(key => key.name);

I don't want to use something like if/else block and copy-pasting the same code twice. Is there any better way to handle this?

The order of methods call matters and should'nt change

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Just add another check inside the .filter callback for whether filtering is active.

salesActivityTypes
     .filter(s => filteringActive ? s.selected : true)
     .map(key => key.name);
about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need an if/else block, and if/else expression is enough and can be part of your chain:

(filteringActive
  ? salesActivityTypes.filter(s => s.selected)
  : salesActivityTypes
).map(key => key.name);

Alternatively, in this particular case you can also pass a no-op callback to filter:

salesActivityTypes
  .filter(filteringActive ? (s => s.selected) : (_ => true))
  .map(key => key.name);
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