I am currently working on a project to create a shopping cart using local storage. I have initialized the local storage with the following code:
var cart = {};
cart.products = [];
localStorage.setItem('cart', JSON.stringify(cart));
I then use AJAX to retrieve product details from an array and add them to the cart upon clicking a button event:
var product = {};
product.id = msg.produto.id;
product.name = msg.produto.nome;
product.price = msg.produto.preco;
product.image = msg.produto.name;
addToCart(product);
The 'addToCart' function appends the product to the existing products in the local storage object using .push
:
var cart = JSON.parse(localStorage.getItem('cart'));
cart.products.push(product);
Next, I need to iterate through all the products stored in the local storage and display their details on the HTML page using either a for
loop or $.each
method in JavaScript:
I attempted the following approach:
localStorage.setItem('cart', JSON.stringify(cart));
var retrievedData = localStorage.getItem("cart");
$.each(retrievedData , function (i, item) {
alert(item.nome);
alert(item.product.nome);
});
However, this approach did not work as expected.
The data retrieved from
var retrievedData = localStorage.getItem("cart");
looks like the following:
{"products":
[
{
"id":"01",
"name":"Product Name 01",
"price":"Product Price 01",
"image":"Product Image 01"
},
{
"id":"02",
"name":"Product Name 02",
"price":"Product Price 02",
"image":"Product Image 02"
}
]
}