如何从角度6的数组中删除重复的对象 [英] How to remove duplicate object from an array in angular 6

查看:58
本文介绍了如何从角度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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆