João Pedro Rodrigues João Pedro Rodrigues - 2 months ago 23
JSON Question

Loop local storage object in javascript

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"
},
]
}

Answer
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 call follow techniques mentioned in Access / process (nested) objects, arrays or JSON to traverse the data structure.

Comments