如何从角度6的数组中删除重复的对象 [英] How to remove duplicate object from an array in angular 6
问题描述
我正在尝试删除数组中的重复值对象,但不起作用...我认为重复功能正在起作用,但未反映在li
列表中.你能找出我要去的地方吗?
I am trying to remove duplicate value objects in an array but not working... I think duplicate function is working but not reflecting in li
list. Can you find out where I have to change?
我的服务文件:
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
的唯一位置,只需在插入之前检查是否存在.永远不会将重复项放入数组中,因此您不必修剪它们.
If addComp
is the only place you modify this.item
, just check for existing prior to insertion. Duplicates will never get put in the array, so you'll never have to trim them.
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
函数的副作用是意外的.但是,您可以做到...
Alternatively, if there are other places that you're modifying this.item
, you should be stripping duplicates in a more expected place. Stripping them as a side-effect of the addComp
function is unexpected. However, you could do it...
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
)
);
}
这篇关于如何从角度6的数组中删除重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!