Angular2:删除数组中的对象

Angular 2: Delete object in Array

当对象的 ID 等于要比较的对象的 ID 时,我想删除数组中的对象。目前,它只删除数组中的第一个对象

if(this.selectedProducts.length > 0){
      for(let x of this.selectedProducts){
          if(prod._id === x._id){
              this.selectedProducts.splice(x,1);   //this is the part where I 'delete' the object
              this.appended = false;
          }else{
              this.appended = true;
          }
      }
      if (this.appended) {
          this.selectedProducts.push(prod);
      }
  }else{
      this.selectedProducts.push(prod);                
  }
  this.selectEvent.emit(this.selectedProducts);
}

this.selectedProducts.splice(x,1); 

splice 的第一个参数必须是索引,而不是对象。

如果您使用 for...of,则无法轻松获取索引。因此,您应该改用常规 for 循环。通过一些额外的简化,您的代码将如下所示:

for (let i = this.selectedProducts.length - 1; i >= 0; this.selectedProducts.length; i--) {
  if (prod._id === this.selectProducts[i]._id) {
      this.selectedProducts.splice(i, 1);   //this is the part where I 'delete' the object
  }
}
this.selectedProducts.push(prod);

很可能使用 filter 会更好:

this.selectedProducts = this.selectedProducts.filter(x => prod._id !== x._id).concat(prod);