javascript - 如何避免数组中的重复对象并仅更新 Angular 2 中的项目数量

标签 javascript arrays angular

我正在尝试找到一种方法来从我的 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 }
]

Plnkr Sample

最佳答案

在将新项目推送到数组之前检查它是否存在。

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/

相关文章:

javascript - 通过 JavaScript 创建新的 HTML5 视频元素

javascript - 响应ajax方法的innerHtml

javascript - Codeigniter-PHP : How to Change table week Dates , 更改输入日期

php - MySQL 多个项目链接到一个 ID

Angular 2 Material : sidenav focus on the first navigation item

angular - 访问自定义表单控件的有效值

javascript - 将正则表达式模式从 Javascript 转换为 PCRE (perl)

arrays - 从 SwiftUI 中的列表中删除绑定(bind)

java - Java 中的数组 - Core Java

Angular 2 - ngModel 不检查复选框