Using Local Storage Data as an Object

I’m working on a food based site where users can manipulate different ingredients in order to see how many calories are in it. All of the various measurements are saved to Local Storage both separately and as one big long string (marked with X in the first image). This all works fine.

The problem arises when I navigate to another page where I want to use the data saved in local storage. In particular, I want to be able to extract those long strings (that contain all of the product data as opposed to a single piece of data), convert them to an object, and then iterate through that object so that I can populate the page. With the code below I am able to get the object I want (as shown in the console log and marked with X in the second image).

let xyz = JSON.stringify(localStorage);
let obj = JSON.parse(xyz);

The page will include several products, so what I would like to know how I can isolate those long objects, and then iterate through them to use the data to populate the page? In affect what I need to end up with is an equivalent to having something like these on the page:

let GreenGrape = {“addedToDish”: true, “foodId”: “food_bncple4a2uagu1b4hov92budz2vs”, “weightPerServing”: 5, “caloriesPerServing”: 3,…etc.}
let AnOtherFood = {“addedToDish”: true, “foodId”: “food_aHuihj4a2uagu1b4hovt7kijsy90f”, “weightPerServing”: 29, “caloriesPerServing”: 65,…etc.}

Any help or suggestions are greatly appreciated. Thank you.


Hello!

What’s the reason to store it separately? I mean, it would be easier if the food wasn’t, right?

Maybe destructuring can help you?

I managed to figure this out and get it to work by using:

// Extract all data saved in local Storage
let xyz = JSON.stringify(localStorage);

// Converts to an object
let obj = JSON.parse(xyz);

// Loop through the object to find what I need
for (const [key, value] of Object.entries(obj)) {}

Hi @skaparate,

I guessed someone would ask that, but hoped they would include an answer to my question also :-).

The reason they are separate is that I am a noob and had written my code based on doing it like this. It was only later I realised I could put all of the data into a single string.

I managed to get it figured out in the end.

1 Like