網站搜尋

在 Angular 2 中,根據索引更新存儲陣列中的項目屬性


我有一個看起來像這樣的物件陣列

0:{price: 43, index: 103}
1:{price: 47, index: 103}
2:{price: 42, index: 103}
3:{price: 45, index: 102}
4:{price: 48, index: 102}
5:{price: 46, index: 102}
6:{price: 44, index: 102}
length:7

該值不應該添加到陣列中,相反,如果索引與陣列的前一個索引匹配,應該更新之前的值,否則該值應該累加到 JSON 陣列中。

0:{price: 42, index: 103}
1:{price: 44, index: 102}
length:2

我現在運行的程式碼如下:

updateValue(prices,indexes) {
    let v = {price: prices,index: indexes};
    this.newPriceList.push(v);
}

答案#1

所以你需要先檢查陣列中是否有該索引的項目。如果有——更新該項目的價格,如果沒有——就將它加入陣列中。

updateValue(prices, indexes) {
   const found = this.newPriceList.find(item => item.index === indexes);

   if (found) {
      found.price = prices;
   } else {
      this.newPriceList.push({ price: prices, index: indexes });
   }
}

答案#2

請執行以下操作

updateValue(prices,indexes)
{
    const oldItem = this.newPriceList.filter(item => item.index === indexes)[0];
    if (oldItem) {
        oldItem.price = prices
    } else {
        const v = {price: prices,index: indexes};
        this.newPriceList.push(v);
    }

}