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

147
Visualizações
Javascript: Conditionally add objects to array in one line

In my JS code I have two booleans, flag1 and flag2. I want to create an array ['a', 'b', 'c'] where a is included only if flag1 is true, and where b is included only if flag2 is true. What I have now is [flag1 ? 'a' : null, 'b', flag2 ? 'c' : null], but if flag1 and flag2 are false this gives me [null, 'b', null] instead of ['b'].

SOLUTION:

Here's the cleanest way I found for doing it: [...(flag1 ? ['a'] : []),'b',...(flag2 ? ['c'] : [])]

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

0

You could take a function which returns either the value inside an array or an empty array for spreading into an array.

const
    either = (condition, value) => condition ? [value] : [],
    getArray = (flag1, flag2) => [
        ...either(flag1, 'a'),
        ...either(flag2, 'b'),
        'c'
    ];
    
console.log(...getArray(true, true));
console.log(...getArray(false, true));
console.log(...getArray(true, false));
console.log(...getArray(false, false));

about 4 years ago · Juan Pablo Isaza Relatório

0

Another one implementation:

const flag1 = true;
const flag2 = false;
const data = [[flag1, 'a'], [flag2, 'b'], [true, 'c']];

const result = data.flatMap(([flag, letter]) => flag ? letter : []);

console.log(result);

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