You need to enable JavaScript to run this app. JavaScript 如何为presentsData新增sumP字段匹配prices计算礼物总价
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 05:06:02