且构网

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

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

更新时间:2021-08-14 09:26:55

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

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