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

如何比较两个对象数组并在匹配时更新第一个数组的对象

问题:匹配并更新数组对象数据

我有两个对象数组,希望当第二个数组存在匹配数据时,更新第一个数组的对应数据。尝试用forEach处理,但遍历response数组的第二个元素时出现错误。

原始数组

第一个数组(待更新)

const body = [{
    slot: "9:00",
    status: "Available",
    clientName: "",
    doctorName: ""
  }, {
    slot: "9:30",
    status: "Available",
    clientName: "",
    doctorName: ""
  }, {
    slot: "1:00",
    status: "Available",
    clientName: "",
    doctorName: ""
  }, {
    slot: "1:30",
    status: "Available",
    clientName: "",
    doctorName: ""
  }
]

第二个数组(匹配数据源)

const response = [{
  clientName: "John Doe",
  doctorName: "Paul Pierce",
  slot: "09:00",
  status: "Not Available"
}, {
  clientName: "James Bond",
  doctorName: "Chris Paul",
  slot: "01:00",
  status: "Not Available"
}]

期望输出

const result = [{
    slot: "9:00",
    status: "Not Available",
    clientName: "John Doe",
    doctorName: "Paul Pierce"
  }, {
    slot: "9:30",
    status: "Available",
    clientName: "",
    doctorName: ""
  }, {
    slot: "1:00",
    status: "Not Available",
    clientName: "James Bond",
    doctorName: "Chris Paul"
  }, {
    slot: "1:30",
    status: "Available",
    clientName: "",
    doctorName: ""
  }
]

问题原因

出错的核心是slot格式不统一:body中的slot是不带前导0的格式(如"9:00"),而response中的slot带前导0(如"09:00"),直接进行字符串匹配会失败,导致第二个元素无法正确匹配,进而引发错误。

解决方法

方法1:遍历更新原数组(forEach)

先统一slot格式,再匹配更新:

// 工具函数:去除slot小时部分的前导0,统一格式
const normalizeSlot = slot => slot.replace(/^0/, '');

// 遍历待更新数组,查找匹配项并更新
body.forEach(item => {
  const targetSlot = normalizeSlot(item.slot);
  const match = response.find(resItem => normalizeSlot(resItem.slot) === targetSlot);
  if (match) {
    item.status = match.status;
    item.clientName = match.clientName;
    item.doctorName = match.doctorName;
  }
});

console.log(body); // 输出符合期望的结果

方法2:生成新数组(map,推荐)

如果不想修改原数组,使用map创建新数组更安全:

const normalizeSlot = slot => slot.replace(/^0/, '');

const result = body.map(item => {
  const targetSlot = normalizeSlot(item.slot);
  const match = response.find(resItem => normalizeSlot(resItem.slot) === targetSlot);
  // 有匹配项则合并数据,无匹配项则保留原数据
  return match ? { ...item, ...match } : { ...item };
});

console.log(result); // 输出符合期望的结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:42:14