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

JavaScript如何对比两个对象数组并在属性匹配时更新值

月份模板数组与接口返回数据合并实现

核心目标:以预置的12个完整月份模板数组为基准,匹配接口返回的month_name相同的项,更新对应total值,接口未返回的月份保留默认total: 0,最终输出顺序和原模板完全一致。


推荐实现(O(n)时间复杂度,性能更优)

先将接口返回的非0月份数据转为键值映射表,单次遍历模板即可完成更新,避免双层循环的性能损耗:

// 预置12个月模板数组
const monthTemplate = [
  { total: 0, month_name: "Jan" },
  { total: 0, month_name: "Feb" },
  { total: 0, month_name: "Mar" },
  { total: 0, month_name: "Apr" },
  { total: 0, month_name: "May" },
  { total: 0, month_name: "Jun" },
  { total: 0, month_name: "Jul" },
  { total: 0, month_name: "Aug" },
  { total: 0, month_name: "Sep" },
  { total: 0, month_name: "Oct" },
  { total: 0, month_name: "Nov" },
  { total: 0, month_name: "Dec" }
];

// 接口返回的total>0的月份数据
const apiMonthData = [
  { total: 4, month_name: "Mar" },
  { total: 1, month_name: "Apr" }
];

// 构建月份名到total值的查找映射
const monthValueMap = new Map(apiMonthData.map(item => [item.month_name, item.total]));

// 遍历模板生成最终结果
const finalMonthData = monthTemplate.map(templateItem => {
  // 匹配到接口数据就更新total,否则保留原模板值
  return monthValueMap.has(templateItem.month_name)
    ? { ...templateItem, total: monthValueMap.get(templateItem.month_name) }
    : templateItem;
});

简易实现(适合极小数据量场景)

如果业务场景对性能无要求,也可以直接用数组find方法做匹配,代码更简短:

const finalMonthData = monthTemplate.map(templateItem => {
  const matchedItem = apiMonthData.find(apiItem => apiItem.month_name === templateItem.month_name);
  return matchedItem ? { ...templateItem, total: matchedItem.total } : templateItem;
});

提示:如果业务允许修改原模板数组,可以直接在遍历模板时给原对象的total赋值,不需要创建新对象,能进一步减少内存占用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:09:14