首页 > 解决方案 > 尝试在我的数组中添加某些键的值以在我的 React 应用程序中使用

问题描述

我有一个对象数组。我想添加一个特定的密钥/对来添加累积存储的总数。

"AllocateStorage": 200,+ "AllocateStorage": 585,+ "AllocateStorage": 103547,=104,242

[{
  "MonitoringState": "disabled",
  "State_Code": 16,
  "State_Name": "running",
  "EbsOptimized": false,
  "EnaSupport": true,
  "AllocateStorage": 200,
  "SourceDestCheck": true,
  "SpotInstanceRequestId": "None",
  "SriovNetSupport": "None",
  "StateReason_Code": "None",
  "StateReason_Message": "None"
},
{
  "MonitoringState": "disabled",
  "State_Code": 16,
  "State_Name": "stopped",
  "EbsOptimized": false,
  "EnaSupport": true,
  "AllocateStorage": 585,
  "SourceDestCheck": true,
  "SpotInstanceRequestId": "None",
  "SriovNetSupport": "None",
  "StateReason_Code": "None",
  "StateReason_Message": "None"
},
{
  "MonitoringState": "disabled",
  "State_Code": 16,
  "State_Name": "running",
  "EbsOptimized": false,
  "EnaSupport": true,
  "AllocateStorage": 103547,
  "SourceDestCheck": true,
  "SpotInstanceRequestId": "None",
  "SriovNetSupport": "None",
  "StateReason_Code": "None",
  "StateReason_Message": "None"
}
]
解决此问题的最佳方法是什么。我已经调查过,.reduce但示例仅显示添加整个数组。

标签: javascriptreactjsmultidimensional-arrayassociative-arrayreduce

解决方案


减少是要走的路:

let total = arr.reduce((total, obj) => {
    return total += obj.AllocateStorage
}, 0);

推荐阅读