I recently discovered javascript object constructors and came across this interesting example while studying the topic. I experimented with it by adding items to a sample product page, and it worked well. However, I encountered an issue where if I added the same item twice, it would group them together and increase the quantity. But what if I want each item to be listed separately?
function Cart(oldcart) {
this.items = oldcart.items || {};
this.add = function (item, id) {
var storeditem = this.items[id];
if (!storeditem) {
storeditem = this.items[id] = { item: item, qty: 0, price: 0 };
}
storeditem.qty++;
storeditem.price = storeditem.item.itemprice * storeditem.qty;
};
}
var cart = new Cart(req.session.cart ? req.session.cart : {});
cart.add(data, id);
req.session.cart = cart;
My interpretation of the code is that it first checks if the newly added item already exists in this.items based on its ID:
var storeditem = this.items[id];
If it doesn't exist, then it creates the item:
if (!storeditem) {
storeditem = this.items[id] = { item: item, qty: 0, price: 0 };
}
However, if I want to list items separately instead of grouping them, how can I modify the this.add method? Simply replacing the line
this.items[id] = { item: item, qty: 0, price: 0 };
with this code causes the new item to replace the existing one. What am I missing in my approach? I prefer not to use jQuery for this task and would like to understand how to achieve it using pure javascript.