1

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

4
  • may be your id comes as one or somehting. I dont see anything related to angular Commented Sep 5, 2017 at 2:10
  • Event emitter is angular though @AniruddhaDas Commented Sep 5, 2017 at 2:52
  • If selectedProducts were a dictionary that whole operation could just be selectedProducts[prod._id] = prod Commented Sep 5, 2017 at 3:16
  • Do not use for ... of for it won't give you the index which you want to use at Array.splice. try with for ... in or forEach. Commented Sep 5, 2017 at 3:19

1 Answer 1

2
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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.