如何从 angular 6 中的数组中删除重复对象
How to remove duplicate object from an array in angular 6
我正在尝试删除数组中的重复值对象但不起作用...我认为重复函数起作用但未反映在 li
列表中。你能找出我需要更改的地方吗?
我的服务文件:
addComp(Names,c){
this.item.push({ name: Names, componentid: c});
this.uniqueArray = this.removeDuplicates(this.item, "name"); //this line issue
this.item=this.uniqueArray; //this line issue
}
如果 addComp
是您修改 this.item
的唯一地方,只需在插入前检查是否存在。重复项永远不会放入数组中,因此您永远不必 trim 它们。
addComp(Names,c){
let item = {name: Names, componentid: c};
if (this.item.find((test) => test.name === Names) === undefined) {
this.item.push(item);
}
}
或者,如果您要修改其他地方 this.item
,您应该在更期望的地方删除重复项。将它们作为 addComp
函数的副作用进行剥离是出乎意料的。但是,你可以做到...
addComp(Names,c){
this.item.push({name: Names, componentid: c});
this.item = this.item.filter((test, index, array) =>
index === array.findIndex((findTest) =>
findTest.name === test.name
)
);
}
const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
这可能会解决您的问题。
this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
这将修复错误
const uniqueObjectArray = [...new Map(arrayOfObjectsWithDuplicates.map(item => [item[key], item])).values()]
这将删除 this.item
中的现有重复项
const item = [...new Set(this.item)];
这是更新的方法。这将在插入之前检查是否存在。如果 item
不在 this.item
中,则 this.item.indexOf(item) = -1
这是防止将重复值对象推入数组的最佳方法
addComp(Names,c){
let item = {name: Names, componentid: c};
if (this.item.indexOf(item) === -1) {
this.item.push(item);
}
}
我正在尝试删除数组中的重复值对象但不起作用...我认为重复函数起作用但未反映在 li
列表中。你能找出我需要更改的地方吗?
我的服务文件:
addComp(Names,c){
this.item.push({ name: Names, componentid: c});
this.uniqueArray = this.removeDuplicates(this.item, "name"); //this line issue
this.item=this.uniqueArray; //this line issue
}
如果 addComp
是您修改 this.item
的唯一地方,只需在插入前检查是否存在。重复项永远不会放入数组中,因此您永远不必 trim 它们。
addComp(Names,c){
let item = {name: Names, componentid: c};
if (this.item.find((test) => test.name === Names) === undefined) {
this.item.push(item);
}
}
或者,如果您要修改其他地方 this.item
,您应该在更期望的地方删除重复项。将它们作为 addComp
函数的副作用进行剥离是出乎意料的。但是,你可以做到...
addComp(Names,c){
this.item.push({name: Names, componentid: c});
this.item = this.item.filter((test, index, array) =>
index === array.findIndex((findTest) =>
findTest.name === test.name
)
);
}
const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
这可能会解决您的问题。
this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
这将修复错误
const uniqueObjectArray = [...new Map(arrayOfObjectsWithDuplicates.map(item => [item[key], item])).values()]
这将删除 this.item
const item = [...new Set(this.item)];
这是更新的方法。这将在插入之前检查是否存在。如果 item
不在 this.item
中,则 this.item.indexOf(item) = -1
这是防止将重复值对象推入数组的最佳方法
addComp(Names,c){
let item = {name: Names, componentid: c};
if (this.item.indexOf(item) === -1) {
this.item.push(item);
}
}