Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push JSON Objects to array in localStorage

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?

like image 732
nielsv Avatar asked Apr 18 '13 13:04

nielsv


People also ask

How do I push an object to an array in localStorage?

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.

Can localStorage store array of objects?

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 .


1 Answers

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.

like image 116
War10ck Avatar answered Sep 23 '22 07:09

War10ck