如何从JavaScript中的数组中删除重复的对象? [英] How to remove duplicates objects from array in javascript?

查看:26
本文介绍了如何从JavaScript中的数组中删除重复的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我创建了一个名为array1的数组.在这个数组中,我列出了多个对象.我想过滤掉array1对象的值作为唯一值,并且需要将ID与它们各自的值组合在一起.我在这里添加了代码,

In my code i have created one array called array1. In this array i have listed multiple objects. I want to filter out array1 objects values as unique and need to group ids with their respective values. I have added my code here,

Array1

var array1 = [
            {
                value:"A",
                id:1
            },
            {
                value:"B",
                id:1
            },
            {
                value:"C",
                id:2
            },
            {
                value:"B",
                id:5
            },
            {
                value:"A",
                id:2
            },
            {
                value:"A",
                id:1
            }
        ];

我想要的结果,

[
            {
                group:"A",
                groupIds:[1, 2]
            },
            {
                group:"B",
                groupIds:[1, 5]
            },
            {
                group:"C",
                groupIds:[2]
            }
        ]

推荐答案

您可以使用 forEach()将对象按值分组,并使用 Set()删除重复的ID来自 groupIds

You can use forEach() to group objects by values and Set() to remove duplicate ids from groupIds

var array1 = [{"value":"A","id":1},{"value":"B","id":1},{"value":"C","id":2},{"value":"B","id":5},{"value":"A","id":2},{"value":"A","id":1}]

var result = [];
array1.forEach(function(e) {
  if(!this[e.value]) (this[e.value] = {group: e.value, groupIds: []}) && result.push(this[e.value])
  this[e.value].groupIds = [...new Set(this[e.value].groupIds.concat(e.id))]
}, {})

console.log(result)

这篇关于如何从JavaScript中的数组中删除重复的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆