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

Time:11-16

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.

CodePudding user response:

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 ['..']

CodePudding user response:

Building up on Henry Walker's answer.
Using the new JavaScript Array.at() method allows you to enter both positive and negative indices. This code:

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

Would simply translate to:

const stats = bio.stats.data.at(-1);

Giving you the last element in the array.

CodePudding user response:

As data object signifies, it has 5 objects in it, you can this particular object at 3rd place as in an array 1st value is stored at index 0. Try using this code to fetch the last object

var lastObject = bio.stats.data[bio.stats.data.length-1].player_id
  • Related