我正在尝试找到一种方法来从我的 array
列表中删除重复的对象并改为更新项目数量属性。我正在将对象推送到我的 sharedService
。
item 组件 -- 但这只会将数量更新 1,但仍会将相同的对象推送到数组中。不确定 if()
是否应该在 addToBasket()
或 SharedService
中,但很确定 if()
语句错误。
如何将唯一对象放入我的数组中,并且仅在您添加相同对象/项目时更新数量?
addToBasket() {
let items = {
id: '123',
quantity: 1
};
if (items) {
items.quantity = parseInt(items.quantity) + 1;
} else {
this.basketArr = {
id: items.name,
quantity: items.quantity
}
}
this.sharedService.itemCollection(items);
}
到目前为止,我的SharedService
只包含array
对象
itemCollection(id) {
this.itemArr.push(id);
console.log(this.itemArr);
}
期望的结果应该看起来像值 2
是更新后的数量。
[{ id: '123, quantity: 2 }]
而不是——
[
{ id: '123, quantity: 2 },
{ id: '123, quantity: 2 }
]
最佳答案
在将新项目推送到数组之前检查它是否存在。
itemCollection(id) {
// check whether id exists
var index = this.itemArr.findIndex(item => item.id === id.id);
if (index > -1) {
// check quantity to determin whether replace the exist one or not
if (id.quantity === this.itemArr[index].quantity) {
return;
} else {
// update quantity for the exist one
this.itemArr[index].quantity = id.quantity;
}
} else {
// add the new item which dosen't exist
this.itemArr.push(id);
}
console.log(this.itemArr);
}
做一切服务
itemCollection(id) {
// check id only
var index = this.itemArr.findIndex(item => item.id === id.id);
if (index > -1) {
this.itemArr[index].quantity = this.itemArr[index].quantity + 1;
} else {
this.itemArr.push(id);
}
console.log(this.itemArr);
}
关于javascript - 如何避免数组中的重复对象并仅更新 Angular 2 中的项目数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397539/