34

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?

nielsv
  • 6,540
  • 35
  • 111
  • 215
  • 1
    Try to use `window.a = [];` and then push like this; `window.a.push(receiveddata)`. Or just store it once in a new "a" at the start of the function. –  Apr 18 '13 at 13:14
  • Are you doing it on the actual input too? `localStorage.setItem('session', window.a);` –  Apr 18 '13 at 13:17
  • what is the type of localStorage ? and It will over ride because you are setting the same value for same key sesssion. – NullPointerException Apr 18 '13 at 13:22

5 Answers5

95

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.

starball
  • 20,030
  • 7
  • 43
  • 238
War10ck
  • 12,387
  • 7
  • 41
  • 54
  • Thanks. Do you know how I can get it out of the localstorage as seperate arrays? – nielsv Apr 18 '13 at 14:05
  • @user1775531 Not sure I'm following you buddy? Get it out as separate arrays? Is it an array of arrays? – War10ck Apr 18 '13 at 15:24
  • @War10ck, Hi, I just stumbled across this and like the idea. Could you have a look at http://stackoverflow.com/questions/17612962/possible-to-cache-json-to-increase-performance-load-time?noredirect=1#comment25639422_17612962 and say whether this would be a suitable method please? – null Jul 12 '13 at 11:56
  • @War10ck super... can you please show the code to check the data in array and if exists i need to work my operation..thanks. – Vishnu Prasad Sep 24 '14 at 05:37
  • @VP That should probably be another question. That's a little out of scope for this answer. If you post another question relating to how to do that, I'll be happy to post an answer. – War10ck Dec 12 '14 at 14:10
  • If you don't want to constantly create arrays in the LS object, gate the serialization with a quick LS check https://i.imgur.com/3DvEAnA.png – Kxmode Nov 09 '18 at 09:04
  • If 'session' in localStorage already have an array then pushing it to 'a' will create array of arrays. Instead you can just do this: var a = JSON.parse(localStorage.getItem('session')); At first you need to check if 'session' is inside localStorage. – Raiyad Raad Jul 10 '21 at 18:26
9

As of now, you can only store string values in localStorage. You'll need to serialize the array object and then store it in localStorage.

For example:

localStorage.setItem('session', a.join('|'));

or

localStorage.setItem('session', JSON.stringify(a));
techfoobar
  • 65,616
  • 14
  • 114
  • 135
7

One thing I can suggest you is to extend the storage object to handle objects and arrays.

LocalStorage can handle only strings so you can achieve that using these methods

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Using it every values will be converted to json string on set and parsed on get

Brugolo
  • 4,685
  • 3
  • 22
  • 14
0
        let items = {
            name: name,
            size: size,
            price: price
        }

        let itemsList = []

        const getCarStorage = localStorage.getItem('productsList')
        if(getCarStorage){
            itemsList = JSON.parse(localStorage.getItem('productsList'))
            itemsList.push(items)
            localStorage.setItem('productsList', JSON.stringify(itemsList))
        }else{
            itemsList.push(items)
            localStorage.setItem('productsList', JSON.stringify(itemsList))
        }

Tengo un objeto llamado items que cambia en función de lo que reciba por parámetros. Una variable itemsList que es un array vacío.

Si no tengo nada en el localStorage, hago push del objeto dentro del array y lo seteo en el localStorage.

Si ya tengo el array creado en el localStorage, me lo guardo en itemsList, hago push de mi objeto items y vuelvo setearlo.

Así, si no tienes una matriz en localStorage, la creas, si la tienes haces push de lo nuevo.

  • this is a english site. Can you please edit your answer and replace your explanation by an english translation of it? – ruud Nov 04 '22 at 07:56
-6
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Rajesh kumar
  • 169
  • 2
  • 3
  • 12