2017-09-05 110 views
0

我想刪除數組中的對象時,該對象的ID等於被比較的對象的ID。目前,它只能在數組中刪除第一個對象角度2:刪除數組中的對象

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

+0

可能是你的ID來作爲一個或服用點。我沒有看到與角度相關的任何事情 –

+0

事件發射器是角度雖然@AniruddhaDas – Char

+0

如果'selectedProducts'是一個字典,整個操作可能只是'selectedProducts [prod._id] = prod' – Pace

回答

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