Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!