João Pedro Rodrigues João Pedro Rodrigues - 1 year ago 87
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

var product = {}; =; = msg.produto.nome;
product.price = msg.produto.preco;
product.image =;


the 'addToCart' function add the array to local storage object with

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

than, I need to do a
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) {



but don't work...

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

"name":"Product Name 01",
"price":"Product Price 01",
"image":"Product Imagem 01"
"name":"Product Name 02",
"price":"Product Price 02",
"image":"Product Imagem 02"

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download