且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 JavaScript 数组中删除重复的对象?

更新时间:2022-04-27 08:49:18

你可以使用一个对象来查找,如果一个对象已经被插入或者没有.

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);