javascript - Edit property of an object in array of objects -


i have class itemcollection stores information purchases. class has array _items property purchases stores. when user adds new purchase in cart class using additem method adds item in _items property if has item method iterates quantity property if not adds new item in array.

problem instead of adding new item in array when other item chosen keeps incrementing quantity property of first item added.

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 called!");         this._items.push(purchase);         console.log(this._items);       }     },     ... 

since purchase doesn't have id, has "item" id, correct find statement should be:

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

it might better rename _items _purchases in order disambiguate

the complete code should 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 called!");     this._items.push(purchase);     console.log(this._items);   } }, 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -