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

如何与另一数组对比后为缺失的月份对象添加Avg属性值?

实现代码

方案1:使用Map实现(性能更优)

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20},
{Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}];

// 构建月份到对应数据的映射
const monthDataMap = new Map(array1.map(item => [item.Month, item]));
// 遍历完整月份列表生成补全后的数组
const fullMonthData = months.map(month => {
    return monthDataMap.get(month) || { Month: month, Avg: 0 }
});

// 如需直接替换原array1,执行以下赋值即可
array1 = fullMonthData;

方案2:使用普通对象实现(兼容性更好)

const monthDataObj = {}
array1.forEach(item => {
    monthDataObj[item.Month] = item
})
const fullMonthData = months.map(month => {
    return monthDataObj[month] || { Month: month, Avg: 0 }
})
array1 = fullMonthData

以上两种方案最终输出的数组顺序和预设的months数组顺序完全一致,查找效率为O(n),适配各种数据量场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:45:04