如何从JavaScript数组中删除重复的对象? [英] How to remove duplicated OBJECTS from JavaScript array?

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

问题描述

从对象数组中删除重复对象的最佳方法是什么?

What's the best way to remove duplicate objects from array of objects?

来自

var arr = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35},
        {"name":"Bob", "age":35},
        {"name":"Joe", "age":17}, 
    ]

删除重复项时,预期结果是

when duplicates removed, the expected result is

res= arr = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35},
        {"name":"Bob", "age":35},
    ]

(5个对象,重复1个,剩余4个).

(5 objects, 1 duplicate, 4 left).

每个对象的属性数量是固定的,每个数组的属性名称相同.但是,从一个数组到另一个数组,它们可能不仅是上述的名称"和年龄",而且属性的名称可以是任何名称.

The number of properties of each object is fixed, the properties names are the same for each array. However, from array to array they may not be just "name" and "age" as above, but the names of the properties could be any.

@Pointy请在语言上将上述问题中的重复单词视为重复"-分别具有相同数量的属性,相同的属性和相同的值的对象.

@Pointy Please treat the duplicate word in the question above as 'duplicate' in the verbal sense - the object with the same number of properties, the same properties and the same values of that properties respectively.

这不是重复的 从JavaScript数组中删除重复项

推荐答案

无论是否已插入对象,都可以使用对象进行查找.

You could use an object for lookup, if an object is alreday inserted or not.

进行更新以获取对象的所有属性,并使用键的值.如果仅应使用某些属性,则建议使用带有相关键的数组,例如

Update for getting all properties of the object and use the values for the key. If only some properties should be used for it, then I suggest to use an array with the relavant keys, like

['name', 'age']

并与

var key = ['name', 'age'].map(function (k) { return a[k]; }).join('|');

var arr = [{ "name": "Joe", "age": 17 }, { "name": "Bob", "age": 17 }, { "name": "Carl", "age": 35 }, { "name": "Bob", "age": 35 }, { "name": "Joe", "age": 17 }],
    filtered = arr.filter(function (a) {
        var key = Object.keys(a).map(function (k) { return a[k]; }).join('|');
        if (!this[key]) {
            return this[key] = true;
        }
    }, Object.create(null));

console.log(filtered);

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

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