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

95
Visualizações
Check if a condition is met before pushing a property into array ReactJS

I was wondering if someone knows a method that would allow me to push a data property into an array if a condition is met. For example, the code I'm using fetches data from an api. The data that I'm looking for specifically are the pictures. Here is my code:

     for (const key in petData.animals) {
        loadedData.push({
          id: key,
          photo: petData.animals[key].photos[0],
          name: petData.animals[key].name,
          description: petData.animals[key].description,
        });
      }

My issue stems from the fact that some of the data entries lack photos. So whenever I actually run the app, I get an error saying that photos is undefined. Is it possible to add a condition (and if so, how?) similar to if photo === undefined => use a default picture or if the photo === true => use the photo from the api?

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

0

The way to do this previous to the last few years was to check incrementally, like so:

for (const key in petData.animals) {
  let photo = defaultPhoto;
  if (petData.animals[key].photos && petData.animals[key].photos[0]) {
    photo = petData.animals[key].photos[0];
  }
  loadedData.push({
    id: key,
    photo: photo,
    name: petData.animals[key].name,
    description: petData.animals[key].description,
  });
}

However, we now have the optional chaining operator (?.) and nullish coalescing operator (??) so we can do this more concisely, like so:

for (const key in petData.animals) {
  loadedData.push({
    id: key,
    photo: petData.animals[key]?.photos?.[0] ?? defaultPhoto,
    name: petData.animals[key].name,
    description: petData.animals[key].description,
  });
}
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