2017-09-05 4 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가 하나 somehting로 제공 될 수있다. 각도와 관련된 것을 보지 못했습니다. –

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