JavaScript 如何为presentsData新增sumP字段匹配prices计算礼物总价
代码问题排查
- 误用
find的返回值:prices.find()返回匹配到的完整礼物对象,不是对象内的price字段,直接赋值给sumP自然会得到对象而非数字 - 仅计算单个礼物:你只取了
s.presents[0],也就是仅计算了每个人第一个礼物的价格,没有遍历presents数组内的所有元素 - find 回调逻辑错误:
find需要回调返回布尔值来判断是否匹配,你把三元表达式写在回调参数里,返回的是数字,完全不符合 find 的运行规则 - reduce 不生效的核心原因:没有针对每个用户的
presents数组做内层求和,逻辑层级写错了
实现方案
性能更优的预映射方案
先把 prices 转成以礼物名为键、价格为值的映射对象,避免重复遍历查找,数据量大时性能优势明显:
// 先生成价格映射表 const priceMap = Object.fromEntries(prices.map(item => [item.present, item.price])); const res = presentsData.map(person => ({ ...person, // 对当前用户的礼物列表求和 sumP: person.presents.reduce((total, presentName) => { // 找不到对应价格的礼物(比如 coal)默认按0计算 return total + (priceMap[presentName] || 0); }, 0) }));
直接用 find 的简洁写法
如果不需要考虑性能,也可以直接在 reduce 里用 find 查找对应价格,更直观:
const res = presentsData.map(person => ({ ...person, sumP: person.presents.reduce((total, presentName) => { const targetPrice = prices.find(item => item.present === presentName)?.price ?? 0; return total + targetPrice; }, 0) }));
这里用了可选链和空值合并运算符,简化了判断逻辑。
最终运行结果
[ { name: "Peter", presents: ["coffee","holidays"], money: 7000, sumP: 1001 }, { name: "Mario", presents: ["car","coal"], money: 300, sumP: 6000 }, { name: "Amanda", presents: ["computer","coal"], money: 300, sumP: 600 }, { name: "David", presents: ["clothes", "car"], money: 2000, sumP: 6080 } ]
内容的提问来源于stack exchange,提问作者foxDev
相关产品推荐
相关产品推荐

