json - 根据角度 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);
}
解决方案
因此,您首先需要检查数组中是否存在具有这些索引的项目。如果是 - 更新该项目的价格,如果不是 - 只需将其添加到数组中。
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 });
}
}
推荐阅读
- windows - 模式作为 powershell 中的输入
- c++ - 使用单链表筛选 Eratosthenes C++
- android - 如何使用变量而不是真实属性名称来描述 Kotlin 中的属性
- search - 优化 Lua 表搜索
- javascript - 如何使用Javascript检查文本是否被CSS截断
- python - Python Pandas - 时间/日期、平均数据和绘制图表
- magento - 更新电子邮件或密码时删除自定义客户属性
- knockout.js - Magento2 Cache HolePunch 定价
- reactjs - 模态中的顺风高度过渡
- jquery - 以两位小数递增的无限计数器