插入数组前怎么通过id判断该项是否存在?

插入数组前怎么通过id判断该项是否存在,有就不插入,没有就插入


arr = [
    {
        id:'1'
    },
    {
        id:'2'
    }
]

obj = {
    id:'2'
}
arr.push(obj)
阅读 1.8k
3 个回答

通过数组的find方法

const id = '2';
if (!arr.find(el => el.id === id)) {
    // 不存在,插入
}

方法应该有很多。

// 方法一:
if (!arr.find(el => el.id === obj.id)) {
  arr.push(obj)
}
console.log(arr)

// 方法二:
if (!arr.some(el => el.id === obj.id)) {
  arr.push(obj)
}
console.log(arr)

// 方法三:
let exist: number = 0
arr.forEach((item: any) => {
  if (item.id === obj.id) {
    exist+=1
  }
})

if (!exist) {
  arr.push(obj)
}

console.log(arr)

// 方法四:
const values: any[] = []
arr.forEach((item: any) => {
  values.push(item.id)
})

if (values.indexOf(obj.id)=== -1) {
  arr.push(obj)
}

console.log(arr)

如果只是push一次可以直接考虑find,
如果要可能会push多个数据可以考虑先map一下, 取出所有id数组, 再通过includes去判断插入

const exists = arr.map(v => v.id);
if (exists.includes(obj.id)) {
    arr.push(obj);
    exists.push(obj.id)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题