删除对象属性不是唯一的数组项 [英] Remove array items where object property is not unique
问题描述
我有一个对象数组,我需要根据 data-itemid
道具删除重复项。
I have an array with objects and I need to remove duplicates based on the data-itemid
prop.
这是我的代码:
const ListItemsUnique = []
ListItems.map(item => {
if (ListItemsUnique.indexOf(item.props['data-itemid']) === -1) {
ListItemsUnique.push(item)
}
});
它返回与以前完全相同的数组,我在做什么错了?
It returns exactly the same array as before, what am I doing wrong?
推荐答案
最简单,最干净的方法是使用临时集存储在映射过程中先前返回到数组的项目。像这样:
The easiest and cleanest way would be to use a temporary set to store which items you have previously returned to your array, while you're mapping through it. Like so:
let tempSet = new Set();
const ListItemsUnique = ListItems.filter(item => {
if(!tempSet.has(item.props['data-itemid'])) {
tempSet.add(item.props['data-itemid']);
return item;
}
});
然后照常进行映射。
let ListItems = [
{name: "A", props: {"data-itemid": 1}},
{name: "B", props: {"data-itemid": 1}},
{name: "C", props: {"data-itemid": 2}},
{name: "D", props: {"data-itemid": 3}},
{name: "E", props: {"data-itemid": 3}},
]; //mock data
let tempSet = new Set();
const ListItemsUnique = ListItems.filter(item => {
if(!tempSet.has(item.props['data-itemid'])) {
tempSet.add(item.props['data-itemid']);
return item;
}
})
console.log(ListItemsUnique.map(item => item.name)); //Items "B" and "E" are skipped
顺便说一句, Set
非常适合处理或希望获得唯一的数据集合。阅读 MDN 有关 Set
的更多信息。
By the way, Set
is great for when dealing with, or wanting to achieve, a unique collection of data. Have a read on the MDN for more info on Set
.
以下是文档的摘录:
Set
对象是值的集合。您可以按插入顺序遍历集合的元素。Set
中的值只能出现一次;它在Set
的集合中是唯一的。
Set
objects are collections of values. You can iterate through the elements of a set in insertion order. A value in theSet
may only occur once; it is unique in theSet
's collection.
这篇关于删除对象属性不是唯一的数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!