如何基于fromSuppliers内的id对嵌套对象中product数组的price求和
解决方案
实现思路
- 先通过
Object.values()提取源对象items字段下的所有订单条目 - 用
reduce方法按供应商id分组累计总价,同步处理两个数据格式问题:- 供应商id的键名是带星号的
**id**,需按特殊键名取值 - price字段存在带
**的字符串、纯数字两种格式,统一清洗为数值类型再累加
- 供应商id的键名是带星号的
- 最后把分组累加的映射对象转换为要求的数组输出格式
完整实现代码
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
相关产品推荐
相关产品推荐

