简体   繁体   中英

How to link shopping cart array with products array?

Here I have array of products which is add products to basket . How can I remove certain product from array after I added it to basket by ID ?

  //Product class
    function Product(options) {
      this.id = options.id;
      this.name = options.name;
      this.cost = options.cost;
      this.quantity = options.quantity;
      this.shortDescription = options.shortDescription;
      this.fullDescription = options.fullDescription;
    }

//Basket class
function Cart() {
  this.items = [];
}

//Add product in basket
Cart.prototype.addItem = function(options) {
  //If we find the same element in array by name, just +1 to quantity in basket
  options.quantity = 1;
  for (var i in this.items) {
    if (this.items[i].id === options.id) {
      this.items[i].quantity += options.quantity;
      return;
    }
  }
  var item = new Product(options);
  this.items.push(item);
};


var arrayOfProducts = [
  {id:1, name:'book', cost:5.45, quantity:5, shortDescription: 'Short description about book', fullDescription: 'Full description about book'},
  {id:2, name:'pan', cost:7.31, quantity:2, shortDescription: 'Short description about pan', fullDescription: 'Full description about pan'},
  {id:3, name:'cup', cost:9.37, quantity:4, shortDescription: 'Short description about cup', fullDescription: 'Full description about cup'},
]

cart.addItem(arrayOfProducts [0]);
cart.addItem(arrayOfProducts [0]);
cart.addItem(arrayOfProducts [1]);

We will see this in the array of Cart

id:1, name:book, cost:5.45, quantity:2, short description: Short description about book, full description: Full description about book
,id:2, name:pan, cost:7.31, quantity:1, short description: Short description about pan, full description: Full description about pan

Firstly, for your Product class you should have another value which reflects a counter for that item. That way, if someone adds two of the same thing, you just increment that counter rather than adding a whole extra instance of the same object.

Then, removing things would be easier. First you check if the item they want to remove has a counter greater than 1. In that case, just decrement the counter. Or, if they only have one instance of that item, remove it using filter:

myArray = myArray.filter(function( obj ) {
    return obj.id!== 1;
});

This creates a new array btw with a new reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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