javascriptarraysstringobjectlocal-storage

Javascript - How to prevent localStorage from storing data as a string?


I'm currently using a set of data that is an array of objects. In order to try and speed up load times, I'm trying to use localStorage to store the data and access it quickly. The big problem is that the data isn't being stored as an array of objects but rather as a string. The data itself looks something like this.

[{id: 1, name: "BP", industry: "oil and gas", indicator: "Board Oversight"}, 
{id: 2, name: "Shell", industry: "oil and gas", indicator: "Board Oversight"}]

This entire array is being stored in a variable called dataSet and I attempted to store it into local storage like so.

localStorage.setItem('finalDataset', dataSet)

When I try to get the item, the data stored inside looks correct but the data is a string as opposed to what I actually want. So how can I store this data inside of localStorage in the exact same format?

I also attempted to do localStorage.setItem('finalDataset', JSON.stringify(dataSet)) and that also returned a string.


Solution

  • Javascript - How to prevent localStorage from storing data as a string?

    You can't, that's what it does.

    What you can do is use a string-friendly serialization format, like JSON.

    To retrieve:

    const data = JSON.parse(localStorage.getItem("name") || "null");
    

    That retrieves and deserializes the data. You get null if there wasn't anything stored for that key. (Technically, you don't even need the || "null" part of that, since localStorage.getItem("name") returns null and JSON.parse coerces its argument to a string, but...I like to include it anyway, for...clarity?)

    To store:

    localStorage.setItem("name", JSON.stringify(data));