javascript 如何获取对象数组中的重复值

wvt8vs2t  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(385)

我有一个对象数组,我想得到,和数组有相同标题的对象,而相同id的对象不能重复,我怎么得到,有什么方法可以得到吗?

products=[{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}]

结果应该是

result=[{_id:1234,title:'carrot',price:90},{_id:789,title:'carrot',price:100}]
nsc4cvqm

nsc4cvqm1#

可以使用reduce和find方法,首先用findIndex删除重复的对象;然后使用reduce方法将对象分组到父对象中,父对象使用title作为属性:

let products=[{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}]
let grouped = products.reduce((acc, cur, i, arr) => {
    if (arr.findIndex(obj => obj._id === cur._id) === i) {
        if (!(cur.title in acc)) {
            acc[cur.title] = []
        }
        acc[cur.title].push(cur)
    }
    return acc
}, {})
console.log(grouped)

结果:

{
  "carrot": [
    {
      "_id": 1234,
      "title": "carrot",
      "price": 90
    },
    {
      "_id": 789,
      "title": "carrot",
      "price": 100
    }
  ],
  "Beans": [
    {
      "_id": 345,
      "title": "Beans",
      "price": 100
    }
  ]
}

参考文件:Array.reduce()/Array.findIndex()

相关问题