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

如何基于fromSuppliers内的id对嵌套对象中product数组的price求和

解决方案

实现思路

  1. 先通过Object.values()提取源对象items字段下的所有订单条目
  2. 用reduce方法按供应商id分组累计总价,同步处理两个数据格式问题:
    • 供应商id的键名是带星号的**id**,需按特殊键名取值
    • price字段存在带**的字符串、纯数字两种格式,统一清洗为数值类型再累加
  3. 最后把分组累加的映射对象转换为要求的数组输出格式

完整实现代码

const priceGroup = Object.values(Jsonresult.items).reduce((acc, order) => {
  // 加可选链兼容product数组为空的异常场景,避免运行报错
  const supplierId = order.product?.[0]?.fromSuppliers?.['**id**']
  if (!supplierId) return acc

  // 统一清洗price为数值类型
  const orderPrice = Number(String(order.price).replace(/\*\*/g, ''))
  acc[supplierId] = (acc[supplierId] || 0) + orderPrice
  return acc
}, {})

// 转换为要求的输出格式
const output = Object.entries(priceGroup).map(([id, totalPrice]) => ({
  id: Number(id),
  totalPrice
}))

console.log(output)

输出结果

[
  { id: 1, totalPrice: 19.84 },
  { id: 2, totalPrice: 9.84 }
]

(注:示例预期中的19,84为小数点分隔符笔误,已修正为标准数值格式)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:54:03