Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I read the first element in an array when the array is a property of an object?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading