I want to implement simple shopping cart system on my site using WebStorage. Items are pictures with format and amount values. There is a counter value which contains the number of items available in the storage at the moment and each new item is added to WebStorage in this format:
item<id> = 1:3,5
Now I have a problem with listing items from the storage. For example, if user buys 5 items and removes item0
and item3
(item -= 2
), I wouldn't be able to get all the values with simple for loop even if I check if element exists in storage:
var len = parseInt(localStorage.getItem("items"));
for (let i = 0; i < len; i++) {
if (localStorage.getItem("item" + i)) {
// show element on the page
}
}
Len will be three, but I'll still have the item5
which wouldn't be showed.
Should I make new array of items' ID and remove ID's as items are deleted from page or there's a better way to deal with this?
It would be best to use a JSON object to handle all of your contents.
Your code would look something like this to set data:
// initial data
var cartData = {
items: ['item1', 'item2', 'item3']
};
// stringify your object so it can be saved into localStorage
localStorage.setItem('cart', JSON.stringify(cartData));
Then you can easily remove/loop through items:
// get cart
var cartData = JSON.parse( localStorage.getItem('cart') );
// delete 2nd item
cartData.items.splice(1, 1);
// loop through items
for(var i = 0, l = cartData.items.length; i < l; i++) {
// do something with cartData.items[i]
}