【问题标题】:How to remove duplicate object from an array in angular 6如何从角度6中的数组中删除重复对象
【发布时间】:2019-05-07 07:47:55
【问题描述】:

我正在尝试删除数组中的重复值对象但不工作...我认为重复函数工作但没有反映在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
 }

【问题讨论】:

    标签: angular typescript angular5 angular6 angular2-services


    【解决方案1】:
    const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
    

    这可能会解决您的问题。

    【讨论】:

      【解决方案2】:
      this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
      

      【讨论】:

        【解决方案3】:

        如果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);
          }
        }
        

        或者,如果您正在修改其他位置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
             )
          );
        }
        

        【讨论】:

        • 谢谢..工作正常
        • 我有一些关于 Angular 6 的问题。你能回答我吗?
        【解决方案4】:

        这将删除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);
          }
        }
        

        【讨论】:

          【解决方案5】:

          这将修复错误

          const uniqueObjectArray = [...new Map(arrayOfObjectsWithDuplicates.map(item => [item[key], item])).values()]
          

          【讨论】:

            猜你喜欢
            • 2019-09-12
            • 2021-10-08
            • 2018-08-15
            • 1970-01-01
            • 2022-12-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-30
            相关资源
            最近更新 更多