Updating Localstorage like a Database

Is there a way to update an array in local storage, much like a database?

Here is my current code:

    saveName() {
        var obj = {
            name: "bob"
        localStorage.setItem('name-tag', JSON.stringify(obj));

Thank you!!

In short, yes, arrays can be stored in local storage as long as you stringify them like you are doing with that object.

However, I will say that local storage is not a database. It is more like a temporary key store and lacks much of the advantages that databases give you… relationships, query language, indexing etc. Plus updating anything beyond a simple array or object could get pretty messy later. Since you have to pull it out of storage, modify it, then resave it.

But to get back to your main question, yes you can store the array in local storage by stringifying it. Then you can get it back out with localStorage.getItem('name-tag'); Convert it back to an array. Modify it as you see fit, then resave it back using setItem().


1 Like

Think it’s particularly important to add “persistance” and “immutable by external forces” to that list…
I can modify my own localStorage by pushing a few buttons on my keyboard, in any way i desire.

That said, perhaps this isnt a case where security of data is important. So back to the OP’s question…

Let’s be clear. You’re not storing an array in local storage. You’re storing a string that is the representation of an array in storage. In fact, what you have here isnt a represntation of an array either, it’s a representation of an Object.
How do you update it? Same way you created it, in reverse. Pull the string out of storage, JSON.parse it back into an object (again, what you’ve got is an object, not an array…), make the changes you need to make, and then commit it back to storage by stringifying it as you’ve already done in the initial creation.


Thank you @Martyr2

@m_hutley Thank you!

And yes, security is not what I’m necessarily looking for. I’m just trying to learn everything I can about local storage :grinning:

1 Like

Update: I think m_hutley already said all of the following.

Are you sure that is an array? See How to Store Data in Web Browser Storage - localStorage and sessionStorage Explained. Arrays are defined using square brackets () and you are using curly brackets ({}).

localStorage data consists of keys and values. An array is stored as a value of a key, usually stringified JSON as you are doing. To update one item in the array the array must be converted to a JavaScript array and then the array can be modified and written back if applicable.

When it comes to “browser storage” , an often overlooked thing is indexedDb, which might fit your needs a bit more:
indexed DB


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.