javascript - JavsScript - 遍历嵌套数组
问题描述
我有一个嵌套的金融投资组合 JSON 文件。我需要从每个持有的所有投资组合帐户中获取 security_type(在示例 JSON 中只有一个),以及每个投资组合的每个个人持有的总净值,所有这些都在一个循环中。
最终,我尝试使用这些信息在饼图中显示,该饼图根据证券类型的净值进行分离。
JSON文件:
{
"id": 1,
"username": "Test",
"portfolio_accounts": [
{
"id": 1,
"user": 1,
"username": "Test",
"account_type": "IRA",
"name": "MyTestAccount",
"description": "Just a Test",
"balance": 100.00,
"holdings": [
{
"id": 1,
"portfolio_id": 2,
"security_type": "Stock",
"ticker": "GOOG",
"price": 1000.50,
"shares": 20,
"purchase_date": "02-20-2021",
"cost_basis": 800.50
},
{
"id": 2,
"portfolio_id": 2,
"security_type": "Bond",
"ticker": "AMZN",
"price": 100.99,
"shares": 4,
"purchase_date": "02-20-2021",
"cost_basis": 60.65
}
]
},
{
"id": 2,
"user": 1,
"username": "Test",
"account_type": "IRA",
"name": "MyTestAccount2 - Electric Boogaloo",
"description": "Repeat",
"balance": 100.00,
"holdings": [
{
"id": 3,
"portfolio_id": 3,
"security_type": "Bond",
"ticker": "GNMA",
"price": 530.50,
"shares": 2,
"purchase_date": "02-20-2021",
"cost_basis": 40.20
}
]
}
]
}
- 库存:(1000.50 * 20) = 20,010 美元
- 债券 1:(100.99 * 4) = 403.96 美元
- 债券 2:(530.50 * 2) = 1,061 美元
- 债券总额:1,464.96 美元
此 JSON 的预期饼图输出示例:
一个饼图,其中一种颜色代表债券(1,464.96 美元),另一种颜色代表股票(20,010 美元),按比例填充。如果有其他安全类型,比如加密,我需要做同样的事情并自动添加第三种颜色(依此类推)。
解决方案
const data =
{ id : 1
, username : 'Test'
, portfolio_accounts:
[ { id : 1
, user : 1
, username : 'Test'
, account_type : 'IRA'
, name : 'MyTestAccount'
, description : 'Just a Test'
, balance : 100.00
, holdings:
[ { id : 1
, portfolio_id : 2
, security_type : 'Stock'
, ticker : 'GOOG'
, price : 1000.50
, shares : 20
, purchase_date : '02-20-2021'
, cost_basis : 800.50
}
, { id : 2
, portfolio_id : 2
, security_type : 'Bond'
, ticker : 'AMZN'
, price : 100.99
, shares : 4
, purchase_date : '02-20-2021'
, cost_basis : 60.65
} ] }
, { id : 2
, user : 1
, username : 'Test'
, account_type : 'IRA'
, name : 'MyTestAccount2 - Electric Boogaloo'
, description : 'Repeat'
, balance : 100.00
, holdings:
[ { id : 3
, portfolio_id : 3
, security_type : 'Bond'
, ticker : 'GNMA'
, price : 530.50
, shares : 2
, purchase_date : '02-20-2021'
, cost_basis : 40.20
} ] } ] }
, security_types = { Stock : 0, Bond : 0 }
;
for(let ptfAcc of data.portfolio_accounts )
for(let hld of ptfAcc.holdings )
security_types[hld.security_type] += (hld.price * hld.shares)
;
console.log( security_types )
推荐阅读
- jquery - 如何多次触发关键帧动画(在每个模糊事件上)?
- c# - 使用列表
动态写入文件:格式问题 - android - Android:如何处理 XML 中的多个根标签?
- visual-studio-2015 - 如何在 Visual Studio 扩展中处理特定文件类型的加载
- php - 检查手机号码CF7
- angular - 找不到模块:错误:无法解析'commonjs-proxy:
- python - 如何使用 python 替换字符串中的 '\N',因为它会导致 unicodeescape 错误?
- python - Python - 从列表下的列表中获取项目
- gradle - 任务“:app:flutterBuildDebug”执行失败
- javascript - 路由器出口导致页面上升,如何解决?