Skip to content
Advertisement

How can I get the last object in this JSON array?

I’m trying to use player data from a football stats API, but I can’t seem to get data for the current season (which can be found in the last object in the array). For some reason I’m only getting data for the third index (code below).

    .then(data => {
        //BIO
        const bio = data['data'][0]
        const nameValue = bio['fullname']
        const imageValue = bio['image_path']
        const teamValue = bio['team']['data']['name']
        const countryValue = bio['nationality']
        const birthdateValue = bio['birthdate']
        const heightValue = bio['height']
        const positionValue = bio['position']['data']['name']
        //STATS
        const stats = bio['stats']['data']['data'.length - 1]
        const appearancesValue = stats['appearences']

Here is an image of the JSON data I am trying to access. In this instance I should be getting data from [4] but I’m getting it from [3].

JSON data Data in browser

I’m quite inexperienced so I feel like I must be making a silly mistake somewhere! Appreciate any help.

Advertisement

Answer

the 'data'.length in the bio['stats']['data']['data'.length - 1] part will evaluate to the length of the "data" string. so it is always 4.

You most likely wanted the length of the array so it should be

bio['stats']['data'][bio['stats']['data'].length - 1]

Or you could extract it beforehand in a variable, for clarity

const dataLength = bio['stats']['data'].length;
const stats = bio['stats']['data'][dataLength - 1];

Also since you are using literals for the object properties you do not need to use the [] notation.

const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];

and you can do that with the rest of the code as well, to avoid typing all the ['..']

Advertisement