I have a function in Javascript:
var a = []; function SaveDataToLocalStorage(data) { var receiveddata = JSON.stringify(data); a.push(receiveddata); alert(a); localStorage.setItem('session', a); }
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?
To push JSON objects into an array in local storage, we can push the object into an array, then we can stringify that array and put it into local storage. For instance, we can write: const a = []; const obj = { foo: 'bar' } a. push(obj); localStorage.
The localStorage API in browsers only supports adding information in a key:pair format and the key and the pair should be of type string thus native objects or arrays cannot be stored in the localStorage .
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:
var a = []; a.push(JSON.parse(localStorage.getItem('session'))); localStorage.setItem('session', JSON.stringify(a));
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:
function SaveDataToLocalStorage(data) { var a = []; // Parse the serialized data back into an aray of objects a = JSON.parse(localStorage.getItem('session')) || []; // Push the new data (whether it be an object or anything else) onto the array a.push(data); // Alert the array value alert(a); // Should be something like [Object array] // Re-serialize the array back into a string and store it in localStorage localStorage.setItem('session', JSON.stringify(a)); }
This should take care of the rest for you. When you parse it out, it will become an array of objects.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With