I’m using IGDB’s API to get a release date for each game that is found from a search, but most games have numerous release dates, so those are all stored in an array, and that array is an object property. When I make a general API request, here is how the data is formatted:
[
{
"id": 5440,
"name": "Kirby Triple Deluxe",
"release_dates": [
{
"id": 16596,
"human": "Jan 11, 2014"
},
{
"id": 16598,
"human": "May 16, 2014"
},
{
"id": 250078,
"human": "May 01, 2014"
}
]
}
]
Here is the code I used to log the entire release_dates array:
const collections = response.data;
collections.forEach(collection => {
console.log(collection.name);
console.log(collection.release_dates);
});
How can I read just the first element in the array? I want to view the "human" property of the first element. One thing I tried was collection.release_dates[0].human but that did not work.
EDIT: To give a bit more clarity: the error I get when I try console.log(collection.release_dates[0].human); within the forEach loop is this: TypeError: Cannot read properties of undefined (reading '0')
>Solution :
Following up on others answers, here is one where you can also rely on fallback.
collections.forEach(collection => {
const releaseDate = collection?.release_dates?.[0] ?? 'No release date.'
});
?? is called nullish coalescing operator. Even if release_dates[0] could be undefined, you can reliably fallback on "No release date." string.