0

I'm developing a shopping cart with local storage, I declare the local storage

var cart = {}; cart.products = []; localStorage.setItem('cart', JSON.stringify(cart));

and add the products with AJAX from a data array with products details on a onclick() 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 add the array to local storage object with .push

var cart = JSON.parse(localStorage.getItem('cart')); cart.products.push(product);

than, I need to do a for or $.each in javascript to get all the products details, one-by-one and add to my html.

I've tried this way:

localStorage.setItem('cart', JSON.stringify(cart));

var retrievedData = localStorage.getItem("cart");

$.each(retrievedData , function (i, item) {

 alert(item.nome);
 alert(item.product.nome);

});

but don't work...

the var retrievedData = localStorage.getItem("cart"); object result lik

{"products":
    [
        {
        "id":"01",
        "name":"Product Name 01",
        "price":"Product Price 01",
        "image":"Product Imagem 01"
        },
        {
        "id":"02",
        "name":"Product Name 02",
        "price":"Product Price 02",
        "image":"Product Imagem 02"
        },
    ]
}

3 Answers3

1

Result from localStorage data you expect is an array which is the value of "products" property of returned object.

For this reason, I would try:

$.each(retrievedData.products , function (i, item) {
  ...
});
MarcoS
  • 17,323
  • 24
  • 96
  • 174
0
var retrievedData = localStorage.getItem("cart");

retrievedData will be a string containing JSON. You have to parse it first to get an object, using JSON.parse.

Then you can follow techniques mentioned in Access / process (nested) objects, arrays or JSON to traverse the data structure.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You can use utility like https://github.com/godban/local-storage-parser to simplify interaction with Local Storage

gotbahn
  • 466
  • 2
  • 4
  • 18