問題描述
從對象數組中刪除重復對象的最佳方法是什么?
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 數組中刪除重復的對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!