编辑对象数组中对象的属性

时间:2015-06-02 20:14:56

标签: javascript arrays underscore.js

我有一个班级itemCollection,用于存储有关购买的信息。此类具有数组_items作为购买商店的属性。当用户在购物车中添加新购买时,使用addItem方法在_items属性中添加该项,如果已经有此项,则此方法会迭代quantity属性,如果不在数组中添加新项目。

问题是,当选择其他项目时,不是在数组中添加新项目,而是保持增加第一项的数量属性。

cartCollection class(object):

var cartCollection = {
    _items: [],
    addItem: function(obj) {
      'use strict';
      var purchase = {
        item: {
          id: obj.id,
          name: obj.name,
          price: obj.price
        },
        thisItemTotal: obj.price,
        quantity: 1
      };
      var result = _.findWhere(this._items, purchase.item.id);
      console.log(result);
      if (typeof result != 'undefined') {
        //console.log(result);
        var index = _.findIndex(this._items, {
          id: result.item.id
        });
        //console.log(index);
        result.quantity++;
        this._items[index] = result;
        this._itemTotalPrice();
      } else if (typeof result === 'undefined') {
        console.log("Im was called!");
        this._items.push(purchase);
        console.log(this._items);
      }
    },
    ...

2 个答案:

答案 0 :(得分:1)

由于购买没有ID,但有一个"项目"使用ID,正确的查找语句应为:

var result = _.find(this._items, function(item) {
   return item.item.id == purchase.item.id;
});

最好将_items重命名为_purchases以消除歧义

完整的代码应该是:

addItem: function(obj) {
  'use strict';
  var purchase = {
    item: _.pick(obj, 'id', 'name', 'price')
    thisItemTotal: obj.price,
    quantity: 1
  };

  var result = _.find(this._items, function(item) {
    return item.item.id == purchase.item.id;
  });

  console.log(result);

  if (result) {
    result.quantity++;
    this._itemTotalPrice();
  }
  else {
    console.log("Im was called!");
    this._items.push(purchase);
    console.log(this._items);
  }
},

答案 1 :(得分:0)

您的findWhere语句已损坏。它应该是:

var result = _.findWhere(this._items, {id:purchase.item.id});
祝你好运