简体   繁体   English

如何获取此 JSON 数组中的最后一个对象?

[英]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).我正在尝试使用来自足球统计 API 的球员数据,但我似乎无法获取当前赛季的数据(可以在数组的最后一个对象中找到)。 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.这是我尝试访问的 JSON 数据的图像。 In this instance I should be getting data from [4] but I'm getting it from [3].在这种情况下,我应该从 [4] 获取数据,但我从 [3] 获取它。

JSON 数据 浏览器中的数据

I'm quite inexperienced so I feel like I must be making a silly mistake somewhere!我很缺乏经验,所以我觉得我一定是在某个地方犯了一个愚蠢的错误! Appreciate any help.感谢任何帮助。

the 'data'.length in the bio['stats']['data']['data'.length - 1] part will evaluate to the length of the "data" string.'data'.lengthbio['stats']['data']['data'.length - 1]部分将计算为所述length的的"data"的字符串。 so it is always 4.所以它总是 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 ['..']你也可以用其余的代码来做到这一点,以避免输入所有的['..']

Building up on Henry Walker's answer.以亨利沃克的回答为基础。
Using the new JavaScript Array.at() method allows you to enter both positive and negative indices.使用新的 JavaScript Array.at()方法允许您输入正索引和负索引。 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.给你数组中的最后一个元素。

正如数据对象所表示的,它有 5 个对象,您可以将此特定对象放在第 3 位,因为在数组中第一个值存储在索引 0 处。尝试使用此代码获取最后一个对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM