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

JavaScript实现Excel VLOOKUP效果,配合indexOf循环匹配ID更新数组值

实现类似Excel VLOOKUP的数组日期更新功能

核心实现逻辑

先提取array1的所有id构成索引数组,遍历array2时通过indexOf()匹配id位置,匹配成功后更新null日期值即可。

完整代码示例

// 示例输入数组
let array1 = [
  {"id":1, "date": "23/11/21"}, 
  {"id":2, "date":"20/11/21"}, 
  {"id":3, "date":"15/11/21"}
]
let array2 = [
  {"id":1, "name": "John", "date": null}, 
  {"id":2, "name": "Max", "date": null}, 
  {"id":3, "name": "Peter", "date": null}
]

// 提取array1的id数组,用于indexOf匹配
const arr1IdList = array1.map(item => item.id)

// 遍历array2做匹配更新
for (let i = 0; i < array2.length; i++) {
  const currentItem = array2[i]
  // 查找当前id在array1中的索引
  const matchIndex = arr1IdList.indexOf(currentItem.id)
  // 匹配成功且日期为null时更新值
  if (matchIndex !== -1 && currentItem.date === null) {
    currentItem.date = array1[matchIndex].date
  }
}

// 输出结果即为预期的array2
console.log(array2)

逻辑说明

  • 提取arr1IdList时顺序和array1完全对应,因此indexOf()返回的索引可以直接定位到array1的匹配元素
  • 额外加了currentItem.date === null的判断,避免覆盖array2中已经存在的日期值,符合需求场景
  • 如果不需要保留array2原有的非空日期,直接去掉该判断即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:06:04