在数组中,过滤重复id的对象

方法一:

const arr = [

{id: 1, name: "张三"},

{id: 2, name: "AAA"},

{id: 3, name: "ZCZ"},

{id: 1, name: "张三"},

{id: 3, name: "ZCZ"}

]

let hash = []

const newArr = arr.reduce((pre, cur)=>{

hash[cur.id] ? '' : hash[cur.id] = true && pre.push(cur)

return pre

}, [])

console.log(newArr)

打印结果:

方法二:

const arr = [

{id: 1, name: "张三"},

{id: 2, name: "AAA"},

{id: 3, name: "ZCZ"},

{id: 1, name: "张三"},

{id: 3, name: "ZCZ"}

]

var newArr = arr.filter((x, index, self) => {

var arrids = []

arr.forEach((item, i) => {

arrids.push(item.id)

})

const retData = arrids.indexOf(x.id) === index

return retData

})

console.log(newArr)

打印结果:

posted @ 2022-05-11 17:56  Hello程序媛  阅读(441)  评论(0)    收藏  举报