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

231
Visualizações
JS: conditionally adding adding in the middle of an array?

If i have an array of data,

const data = [
   {
     name: "dog",
     age: 11
   }, 
   {
     name: "cat",
     age: 21,
   }
]

I want to add an object in the middle of that if a condition is true:

const shouldAddNewAnimal = true;

const animal = {
   name: "tiger",
   age : 22,
}

How would I write that without an else ?

const data = [
   {
     name: "dog",
     age: 11
   }, 
   foo ? animal : {};
   {
     name: "cat",
     age: 21,
   }
]

above is the only way I can think of writing it but I dont want to insert an empty object in there if the condition is not true.

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

0

You could spread with arrays, one with the wanted object and the other empty.

const
    shouldAddNewAnimal = true,
    animal = { name: "tiger", age: 22 },
    data = [
        { name: "dog", age: 11 },
        ...(shouldAddNewAnimal ? [animal] : []),
        { name: "cat", age: 21 }
    ];

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a spread operator:

const foo = true;
const animal = { name: "mouse", age: 10 };

const data = [
   {
     name: "dog",
     age: 11
   }, 
   ...(foo ? [animal] : []),
   {
     name: "cat",
     age: 21,
   }
]

console.log(data);

This will result in the animal being extracted out of its enclosing array and added to the "outer" array.

In the case of "else" path, spreading the null will result in nothing being added to the "outer" array.

about 4 years ago · Juan Pablo Isaza Relatório

0

You may achieve this by adding null's and filtering them out like so using filter

const shouldAddNewAnimal = false;
const animal = {
   name: 'parrot',
   age:12
}

let data = [
   {
     name: "dog",
     age: 11
   }, 
   shouldAddNewAnimal ? animal : null,
   {
     name: "cat",
     age: 21
   }
].filter(item => item !== null);

console.log(data);

const shouldAddNewAnimal = true;
    const animal = {
       name: 'parrot',
       age:12
    }

    let data = [
       {
         name: "dog",
         age: 11
       }, 
       shouldAddNewAnimal ? animal : null,
       {
         name: "cat",
         age: 21
       }
    ].filter(item => item !== null);

    console.log(data);

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