Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

87
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda