You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用中如何累加数组对象指定键AllocateStorage的值?

累加对象数组中指定键值的最优方案

嘿,你选reduce就对了!这正是处理这类累加需求的最优方式——它不仅能处理纯数字数组,对对象数组的指定键值累加同样得心应手,而且代码简洁、性能出色。

实现代码示例

先把你的数组定义好:

const instanceArray = [
  { "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完成累加:

const totalStorage = instanceArray.reduce((accumulator, currentItem) => {
  // 把当前对象的AllocateStorage值加到累加器里
  return accumulator + currentItem.AllocateStorage;
}, 0); // 初始值设为0,确保数组为空时返回0而非undefined

console.log(totalStorage); // 输出:104242

代码解释

  • accumulator:就是我们的“总和容器”,每次遍历都会把当前项的目标值加进去
  • currentItem:当前正在遍历的数组对象,我们从中取出AllocateStorage的值
  • 最后的0是累加器的初始值,这个非常关键——如果不设置,当数组为空时会返回undefined,而且如果第一个对象的AllocateStorage是字符串类型(虽然你的示例里是数字),还可能出现字符串拼接的问题。

额外小提示

如果你的数组里可能存在没有AllocateStorage键的对象,可以加个容错判断,避免报错:

const totalStorage = instanceArray.reduce((accumulator, currentItem) => {
  return accumulator + (currentItem.AllocateStorage || 0);
}, 0);

这样即使某个对象没有这个键,也会默认加0,不会影响最终结果。

内容的提问来源于stack exchange,提问作者Amen Ra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:34:26