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

JavaScript中如何匹配数组更新对象,无匹配项则新增对象

JavaScript实现数组元素匹配更新或新增

实现思路

  • 首先遍历目标数组,匹配同时满足name和alertType两个字段相等的元素
  • 匹配到对应元素时,直接更新该元素的selected属性值
  • 未匹配到对应元素时,将新对象追加到数组末尾

可修改原数组的实现

function upsertObject(targetArr, newObj) {
  // 查找匹配项
  const matchedItem = targetArr.find(item => 
    item.name === newObj.name && item.alertType === newObj.alertType
  )
  if (matchedItem) {
    // 匹配成功,更新selected属性
    matchedItem.selected = newObj.selected
  } else {
    // 无匹配项,新增元素
    targetArr.push(newObj)
  }
}

// 测试用例
const target = [
  {name: 'srk@gmail.com', selected: false, alertType: 'max'},
  {name: 'abc@gmail.com', selected: true, alertType: 'clear'},
]
// 测试无匹配项的场景
const newObject = {name: 'srk@gmail.com', selected: false, alertType: 'both'}
upsertObject(target, newObject)
console.log(target) // 数组长度变为3,新增对应对象

// 测试有匹配项的场景
const updateObject = {name: 'abc@gmail.com', selected: false, alertType: 'clear'}
upsertObject(target, updateObject)
console.log(target) // abc元素的selected属性更新为false

不修改原数组的 immutable 实现

如果你不想改动原数组,可以使用下面的版本,会返回新数组:

function upsertObjectImmutable(targetArr, newObj) {
  const matchIndex = targetArr.findIndex(item => 
    item.name === newObj.name && item.alertType === newObj.alertType
  )
  if (matchIndex > -1) {
    // 匹配成功,替换对应位置元素的selected属性
    return [
      ...targetArr.slice(0, matchIndex),
      {...targetArr[matchIndex], selected: newObj.selected},
      ...targetArr.slice(matchIndex + 1)
    ]
  } else {
    // 无匹配项,追加新元素返回
    return [...targetArr, newObj]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:24:07