Json 在索引到angular 2中存储的数组时更新项属性
我有一个像这样的对象数组Json 在索引到angular 2中存储的数组时更新项属性,json,angular,typescript,Json,Angular,Typescript,我有一个像这样的对象数组 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 该值不应添加到数组中,相反,如果索引与数组的上一个索引匹配,则应更新上一个值,否则该值应添
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 });
}
}
请做以下事情
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);
}
}
下面是使用方法执行此操作的另一种方法:
arr = [{price: 43, index: 103},
{price: 47, index: 103},
{price: 42, index: 103},
{price: 45, index: 102},
{price: 48, index: 102},
{price: 46, index: 102},
{price: 43, index: 102}];
processed = arr.reduce((acc, v) => {
acc[v.index] = v;
return acc;
}, {});
result = Object.values(processed);
console.log(result );
//=> Array [Object { price: 43, index: 102 }, Object { price: 42, index: 103 }]