My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Create an array of objects from LocalStorage

andyshah's photo
andyshah
·Apr 27, 2019

I build an array of objects in Javascript then store that in LocalStorage. I want to now rebuild that when the user returns.

So to start with:

var cartItems = {};
var items = []
cartItems.items = items;

I push, update as and when required. So I end up with an array like this:

{"items":[{"name":"Bronze Car","price":2.99,"quantity":1},{"name":"Paris Delight","price":3.99,"quantity":1},{"name":"Lamp Frost","price":5.8,"quantity":2}]}

Write to LocalStorage:

localStorage.setItem('productsInCart', JSON.stringify(cartItems));

The difficulty I am having is setting the cartItems to that above array if LocalStorage exists. I was hoping it would be like this:

if (localStorage.getItem("productsInCart") === null) {
var cartItems = {};
var items = []
cartItems.items = items;
}
else
{
var cartItems = JSON.parse(localStorage.getItem("productsInCart"));

Then I could just continue pushing and updating etc. But that does not work, how can I recreate the cartItems structure and set it to cartItems so I can push etc.

I would then push items to that array as objects.

var item = {
"name": name,
 "price": price,
 "quantity": quantity
}
cartItems.items.push(item);