Angular 2: Delete object in Array

3k views Asked by At

I want to delete an object in an array when that object's ID is equal to the ID of the object getting compared. Currently, it only removes the first object in the array

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

1

There are 1 answers

0
AudioBubble On BEST ANSWER
this.selectedProducts.splice(x,1); 

The first parameter to splice must be the index, not the object.

If you're using for...of, you can't get the index easily. So you should use a regular for loop instead. With some additional simplifications, your code would look like this:

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);

It's highly likely that using filter would be better anyway:

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