Skip to content
Advertisement

Push JSON Objects to array in localStorage

I have a function in Javascript:

JavaScript

the data parameter is a JSON Object.

But everytime I click the button it overwrites the data in my localstorage.

Does anybody know how to do this?

Advertisement

Answer

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

JavaScript

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

JavaScript

This should take care of the rest for you. When you parse it out, it will become an array of objects.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement