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

JavaScript中如何在同一个函数内结合使用map和reduce获取商品总价?

问题原因

  • 取值路径错误:productM数组的单个元素结构为{ product: { price: {...} } },原代码中p.price.amount跳过了product层级,正确路径应为p.product.price.amount。
  • 二维数组未处理:两次嵌套map调用返回的是二维数组,直接用reduce累加会出现类型不匹配问题,无法得到正确结果。

修复后代码

function getTotalPrice(products) {
  // 用flatMap替代外层map,直接将内层map返回的数组合并为一维数组
  const amountList = products.flatMap((product) =>
    product.productM.map((p) => p.product.price.amount)
  );
  return amountList.reduce(
    (accumulator, current) => accumulator + current,
    0
  );
}

// 测试调用,输出结果为122
console.log(getTotalPrice(products))

简化方案

如果你只是需要取出当前示例数据里的122值,不需要做全量累加,可以直接通过固定路径访问:
const targetAmount = products[0].productM[0].product.price.amount

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:45:03