首页 > 解决方案 > 根据角度 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);
}

标签: jsonangulartypescript

解决方案


因此,您首先需要检查数组中是否存在具有这些索引的项目。如果是 - 更新该项目的价格,如果不是 - 只需将其添加到数组中。

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

推荐阅读