如何解决推送值及其之后替换的问题?



如果存在,如何解决此代码中所选商品的某些问题。例如,用户插入选定的商品或服务的数量,设备ID等,一切都很好。但是,当用户想用另一个设备ID在下一行添加一些选定的商品时,它只会替换现有的选定商品并在其中添加更多数量,但以前的设备ID保持领先。如何解决这个问题?多谢。

addItem() {
if (this.ListOfUsedMaterials.length) {
let exists: boolean = false;
this.ListOfUsedMaterials.forEach(item => {
if (item.goodId == this.selectedGood.id) {
exists = true;
item.quantity += Number(this.item.quantity);
this.item.quantity = "";
this.selectedGood = "";
}
});
if (!exists) {
this.ListOfUsedMaterials.push({
title: this.selectedGood.value,
quantity: Number(this.item.quantity),
goodId: this.selectedGood.id,
unit: this.selectedGood.unit,
device: this.deviceTypId,
manufacturer: this.deviceManufacturerId,
mark: this.deviceMark
});
this.onClear(event);
console.log('Ovo :', this.ListOfUsedMaterials);
//this.item.quantity = "";
//this.selectedGood = "";
}
} else {
this.ListOfUsedMaterials.push({
title: this.selectedGood.value,
quantity: Number(this.item.quantity),
goodId: this.selectedGood.id,
unit: this.selectedGood.unit,
device: this.deviceTypId,
manufacturer: this.deviceManufacturerId,
mark: this.deviceMark
});
console.log('Ovo :', this.ListOfUsedMaterials);
}
}

您只需要通过两个键(goodIddevice(匹配项目即可。下面是代码的更简洁版本:

addItem() {
const found = this.ListOfUsedMaterials.find(item => 
item.goodId == this.selectedGood.id && item.device == this.deviceTypId);
if (found) {
found.quantity += Number(this.item.quantity);
this.item.quantity = "";
this.selectedGood = "";
} else {
this.ListOfUsedMaterials.push({
title: this.selectedGood.value,
quantity: Number(this.item.quantity),
goodId: this.selectedGood.id,
unit: this.selectedGood.unit,
device: this.deviceTypId,
manufacturer: this.deviceManufacturerId,
mark: this.deviceMark
});
this.onClear(event);
}
}

最新更新