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

如何按规则合并两个含日期键的数组对象生成新数组

合并两个数组的日期数据,填充null值

原始数组结构

let array1 = [
  {
    '2023-08-03': { x: 179.159093242013, y: null },
    '2023-08-04': { x: 178.323000340271, y: 55.727942469807 },
    '2023-08-05': { x: null, y: 56.727774687963 },
    '2023-08-06': { x: 182.232246437691, y: 48.911777872434 },
    '2023-08-07': { x: null, y: null },
    '2023-08-08': { x: 180.147793830328, y: 57.752356407584 },
    '2023-08-09': { x: null, y: 47.714833999144 }
  }
] 
let array2 = [
  {
    '2023-07-03': { x: null, y: 45.2 },
    '2023-07-04': { x: 180.55307760927744, y: 48.4 },
    '2023-07-05': { x: 180.04640371229698, y: 55.8 },
    '2023-07-06': { x: 180.53989728172365, y: 57.4 },
    '2023-08-07': { x: null, y: null },
    '2023-07-08': { x: 168.59344894026975, y: 37.3 },
    '2023-07-09': { x: 178.7709497206704, y: 57.9 }
  }
]

合并规则

  • 若array1中某日期的x值为null,则取array2中月日相同的日期的x值(如2023-08-03对应array2的2023-07-03)
  • 若array1中某日期的y值为null,则取array2中月日相同的日期的y值
  • 若array1中某日期的x和y值均不为null,直接保留原数据

预期输出

let newArray = [{
    '2023-08-03': { x: 179.159093242013, y: 45.2 },
    '2023-08-04': { x: 178.323000340271, y: 55.727942469807 },
    '2023-08-05': { x: 180.04640371229698, y: 56.727774687963 },
    '2023-08-06': { x: 182.232246437691, y: 48.911777872434 },
    '2023-08-07': { x: null, y: null },
    '2023-08-08': { x: 180.147793830328, y: 57.752356407584 },
    '2023-08-09': { x: 178.7709497206704, y: 47.714833999144 }
}
]

解决方案

核心逻辑是先把array2的日期按「月日」建立映射表,再遍历array1的每个日期,按规则填充null值:

// 把array2的日期转换为月日->数据的映射,方便快速查找
const array2MonthDayMap = {};
if (array2[0]) {
  Object.keys(array2[0]).forEach(date => {
    const monthDay = date.slice(5); // 提取MM-DD部分
    array2MonthDayMap[monthDay] = array2[0][date];
  });
}

// 处理array1生成新数组
const newArray = [
  Object.fromEntries(
    Object.entries(array1[0]).map(([date, item]) => {
      const monthDay = date.slice(5);
      const matchedArray2Item = array2MonthDayMap[monthDay] || {};
      return [
        date,
        {
          x: item.x !== null ? item.x : matchedArray2Item.x ?? null,
          y: item.y !== null ? item.y : matchedArray2Item.y ?? null
        }
      ];
    })
  )
];

console.log(newArray);

代码说明

  1. 映射表构建:将array2的日期按MM-DD分组,避免每次查找都遍历array2,提升效率
  2. 遍历处理:用Object.entries拆解array1的日期键值对,逐个判断x/y是否为null,若为null则从映射表中取对应月日的数据填充
  3. 兜底处理:若array2中无对应月日的数据,或对应数据也为null,则保留原null值

内容的提问来源于stack exchange,提问作者Vishnu narayanan m

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:22:19