【发布时间】: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<a[i].shareholders应该是j<a[i].shareholders.length -
使用
forEach(),代码会更简单,更不容易出错。 -
是的,我是 JS 新手,所以需要习惯 forEach(),但会尝试一下,谢谢
标签: javascript json axios javascript-objects