【问题标题】:How to access the data from JSON如何从 JSON 访问数据
【发布时间】:2021-09-24 18:52:20
【问题描述】:

我正在访问对象内的数组中的对象的值。下面是数据的格式:

 [{
    "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be",
    "stock_name": "Just Energy Group, Inc.",
    "shareholders": [{
        "userId": "e9328bb2-81ac-4e86-9ec8-520b1909cc9b",
        "number_of_shares": 266
    }, {
        "userId": "d42ff6a6-9b2f-4561-ac2e-0cf2bb170430",
        "number_of_shares": 389
    }]
}]

下面是我使用 axios 从 github 获取数据并打印出用户 ID 的代码:

const axios = require('axios')
require("util").inspect.defaultOptions.depth = null;
async function getStocks(){
    const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/8c363d85e61863ac044097c0d199dbcc/raw/7d79752a9342ac97e4953bce23db0388a39642bf/stocks.json')
    return data // this will be the array of people objects
}
async function listShareholders() {
    let c=[]
    let a = await getStocks();
    for(i=0;i<a.length;i++){
        for(j=0;j<a[i].shareholders;j++)
            c.push((a[i].shareholders[j].userId))
    }
    return c 
    
}
async function bc(){
    const address = await listShareholders()
    console.log(address)
} 

bc()

不知道为什么我没有输出。

【问题讨论】:

  • j&lt;a[i].shareholders 应该是j&lt;a[i].shareholders.length
  • 使用forEach(),代码会更简单,更不容易出错。
  • 是的,我是 JS 新手,所以需要习惯 forEach(),但会尝试一下,谢谢

标签: javascript json axios javascript-objects


【解决方案1】:

已编辑

我正在编辑以包含消失的原始答案(不是我发布的)中的代码

在for(j=0;j&lt;a[i].shareholders;j++),您将number 与Array 进行比较。这是正确的代码:

for(i=0;i<a.length;i++){
     for(j=0; j < a[i].shareholders.length; j++)
         c.push((a[i].shareholders[j].userId);
}

我的答案

正如for(j=0;j&lt;a[i].shareholders;j++) 所指出的,您将number 与Array 进行比较。

建议的解决方案有效,但请记住,您可以在一行中完成:

const c = a.flatMap(obj => obj.shareholders.map(s => s.userId));

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多