typescript 如何从角度为 6 的数组中删除重复的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53637425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove duplicate object from an array in angular 6
提问by SRANSV
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?
我正在尝试删除数组中的重复值对象但不起作用...我认为重复函数正在运行但未反映在li
列表中。你能找出我必须改变的地方吗?
My service file:
我的服务文件:
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
}
回答by Devang Patel
const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
This might be fix your issue.
这可能会解决您的问题。
回答by user2642281
this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
回答by Ian MacDonald
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
是您修改的唯一地方this.item
,只需在插入前检查是否存在。重复项永远不会放入数组中,因此您永远不必修剪它们。
addComp(Names,c){
let item = {name: Names, componentid: c};
if (this.item.find((test) => test.name === Names) === undefined) {
this.item.push(item);
}
}
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...
或者,如果您正在修改其他地方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
)
);
}