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')
4
Answers
I wonder why this didn’t work according to the asker.
Looks like your object is part of a top-level array itself…
i guess you referred to that array as "collection", didnt you?
if that array (that contains your object) is referenced under "collection" you should be able to acces it with
Let me know if it worked
In some cases if
release_dates
key is not present in the object, it will throwundefined
error. So, you should use optional chaining.Following up on others answers, here is one where you can also rely on fallback.
??
is called nullish coalescing operator. Even ifrelease_dates[0]
could beundefined
, you can reliably fallback on "No release date." string.