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

如何获取嵌套数组元素索引及指定ID项VALOR值并实现求和

问题原因分析

你原代码的核心问题是误用了filter方法:filter的作用是返回符合条件的原数组元素集合,你外层用filter包裹,最终只会拿到ProdutoAdicionais里的外层对象,根本无法得到内层累加的数值,逻辑方向错了。

正确实现代码

可以通过flatMap先打平内层Itens数组,再过滤选中项,最后累加取值,实现逻辑非常清晰:

const ValorAdicionas = ProdutoAdicionais
  // 把所有外层分组下的Itens数组合并为一个一维数组
  .flatMap(group => group.Itens)
  // 筛选出ID在选中列表里的项
  .filter(item => adicionaisChecked.includes(item.ID))
  // 累加所有选中项的Valor值
  .reduce((total, current) => total + current.Valor, 0)

兼容低版本环境的写法

如果运行环境不支持ES2019的flatMap方法,可以用reduce替代实现数组打平:

const ValorAdicionas = ProdutoAdicionais
  .reduce((allItens, group) => allItens.concat(group.Itens), [])
  .filter(item => adicionaisChecked.includes(item.ID))
  .reduce((total, current) => total + current.Valor, 0)

效果验证

比如adicionaisChecked = [0, 2]时,运行代码得到的结果就是10,和预期的选中「Morango」+「Biz de Chocolate」的总价值一致。


内容的提问来源于stack exchange,提问作者Matheus Martins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:24:00