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?
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,
});
}