简体   繁体   English

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

[英]Edit property of an object in array of objects

I have a class itemCollection that stores information about purchases. 我有一个itemCollection ,用于存储有关购买的信息。 This class has array _items as property where purchases are stores. 此类具有_items数组作为存储购买的属性。 When user adds new purchase in cart this class using addItem method that adds that item in _items property if its already has this item this method iterates quantity property if not adds new item in array. 当用户在购物车中添加新购买的商品时,该类使用addItem方法将该商品添加到_items属性中(如果该商品已经具有此商品),则该方法将迭代quantity属性(如果未在数组中添加新商品)。

Problem is that instead of adding new item in array when other item is chosen its keeps incrementing quantity property of a first item that was added. 问题是,当选择其他项目时,与其在数组中添加新项目,不如增加添加的第一个项目的数量属性。

cartCollection class (object): cartCollection类(对象):

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);
      }
    },
    ...

Since purchase doesn't have an ID, but has an "item" with an ID, The correct find statement should be: 由于购买没有ID,但有一个带有ID的“商品”,正确的find语句应为:

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

It might be better to rename _items to _purchases in order to disambiguate 最好将_items重命名为_purchases以便消除歧义

The complete code should be something like: 完整的代码应类似于:

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);
  }
},

Your findWhere statement is broken. 您的findWhere语句已损坏。 It should be: 它应该是:

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

Good luck 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM