微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavsScript - 循环遍历嵌套数组

如何解决JavsScript - 循环遍历嵌套数组

我有一个金融投资组合的嵌套 JSON 文件。我需要从每个投资组合中获取所有投资组合账户的 security_type(在示例 JSON 中只有一个),以及每个投资组合的每个单独持有的总净值,所有这些都在一个循环中。

最终,我尝试使用此信息显示在基于证券类型净值的饼图中。

JSON 文件

{
    "id": 1,"username": "Test","portfolio_accounts": [
        {
            "id": 1,"user": 1,"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,"security_type": "Bond","ticker": "AMZN","price": 100.99,"shares": 4,"cost_basis": 60.65
                }
            ]
        },{
            "id": 2,"name": "MyTestAccount2 - Electric Boogaloo","description": "Repeat","holdings": [
                {
                    "id": 3,"portfolio_id": 3,"ticker": "GNMA","price": 530.50,"shares": 2,"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,security_type : 'Bond',ticker        : 'AMZN',price         : 100.99,shares        : 4,cost_basis    : 60.65
      } ] },{ id           : 2,name         : 'MyTestAccount2 - Electric Boogaloo',description  : 'Repeat',holdings: 
        [ { id            : 3,portfolio_id  : 3,ticker        : 'GNMA',price         : 530.50,shares        : 2,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 )

,

您可以创建一个对象,将所有可能的安全类型设置为 0,然后将每个持有的对象相加,例如

let data = {
    "id": 1,"username": "Test","portfolio_accounts": [
        {
            "id": 1,"user": 1,"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,"security_type": "Bond","ticker": "AMZN","price": 100.99,"shares": 4,"cost_basis": 60.65
                }
            ]
        },{
            "id": 2,"name": "MyTestAccount2 - Electric Boogaloo","description": "Repeat","holdings": [
                {
                    "id": 3,"portfolio_id": 3,"ticker": "GNMA","price": 530.50,"shares": 2,"cost_basis": 40.20
                }
            ]
        }
    ]
};
let security_types = {
  Bond: 0,Stock: 0,Crypto: 0
};
data.portfolio_accounts.forEach(portfolio_account => {
  portfolio_account.holdings.forEach(holding => {
    security_types[holding.security_type] += holding.price * holding.shares;
  });
});
console.log(security_types);

,

灵活解决方案的忠实粉丝,所以这里有一个使用 object-scan

// const objectScan = require('object-scan');

const data = { id: 1,username: 'Test',portfolio_accounts: [{ id: 1,user: 1,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,security_type: 'Bond',ticker: 'AMZN',price: 100.99,shares: 4,cost_basis: 60.65 }] },name: 'MyTestAccount2 - Electric Boogaloo',description: 'Repeat',holdings: [{ id: 3,portfolio_id: 3,ticker: 'GNMA',price: 530.50,shares: 2,cost_basis: 40.20 }] }] };

const r = objectScan(['portfolio_accounts[*].holdings[*]'],{
  reverse: false,filterFn: ({
    value: { shares,price,security_type: securityType },context: { holdings,totals }
  }) => {
    const netWorth = shares * price;
    holdings.push({ [securityType]: netWorth });
    if (!(securityType in totals)) {
      totals[securityType] = 0;
    }
    totals[securityType] += netWorth;
  }
})(data,{
  holdings: [],totals: {}
});

console.log(r);
/* =>
{
  holdings: [ { Stock: 20010 },{ Bond: 403.96 },{ Bond: 1061 } ],totals: { Stock: 20010,Bond: 1464.96 }
}
 */
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@14.0.0"></script>

免责声明:我是object-scan

的作者

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。