2017-10-07 4 views
1

私はフレームワークとしてAngularを使用しています。配列が変更されたときに呼び出される関数があります。この関数が呼び出されるたびに配列が重複しているかどうかを確認し、元の項目を編集して最後の項目を配列から削除する必要があるかどうかを調べる必要があります。重複した項目がある場合は配列をチェックし、元の項目を変更して最後の重複する項目を削除する必要がある場合は

私はショッピングカートを構築しています。重複した項目が配列に追加されると、元の項目の量の値を変更し、最後に押された項目を削除する必要があります。

コンポーネント機能:オブジェクトの例の

ngDoCheck() { 
    var changes = this.differ.diff(this.shoppingCart); // check for changes 
    if (changes) { 
     clearTimeout(this.timer); 
     this.cartOpen = true; 
     this.itemsInCart = this.numberOfItemsinCart(this.shoppingCart); 
     this.cartTotal = this.totalCartAmount(this.shoppingCart); 

    //check if this.shoppingCart has a duplicate item 
    //if array does have a duplicate 
    //change qty value in original item and 
    //remove the last item added 

    } 
} 

マイ配列:私はアイデアのうち、AMまたはあまりにも長い間、このコードを見つめてきたよう

{ 
    "id": 6, 
    "product_name": "name of product", 
    "sku": "26-008b", 
    "description": "description of product", 
    "product_link": "link", 
    "cat_id": "categoryId", 
    "cat_name": "Category name", 
    "related_products": [], 
    "sub_cat_name": "sub category name", 
    "price": price, 
    "qty": 1 
} 

すべてのヘルプはいただければ幸いです。

+0

前に複製を制御して、新しいレコードを配列に挿入するか、既存のrを更新するecordは合理的です。 –

+1

ここに私の答えを見てください。役立つ場合は、私の答えを確認してください:https://stackoverflow.com/questions/46087273/angular-2-remove-duplicate-values-from-an-array –

答えて

1

あなたが代わりに追加した後に項目を削除するの配列Array.indexOf(item)Array.prototype.lastIndexOf(item)

if(Array.indexOf(item) == Array.prototype.lastIndexOf(item)) { 
    // change value in position given by indexOf 
    // delete last index 
} 
1

についてjavascriptのbuildinの機能を使用することができ、あなたはそれを追加する前に、重複する項目をチェックする必要があり、

あなたが重複した項目についてチェックすることができ.filterを使用して

var duplicates = this.shoppingCart.filter(this.product_name ==='yourSampleName'); 
if(duplicates && duplicates.length > 0){ 
//add items here 
this.shoppingCart.push(whatever); 
} 
関連する問題