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?

3
  • 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.
    – user1467267
    Apr 18, 2013 at 13:14
  • Are you doing it on the actual input too? localStorage.setItem('session', window.a);
    – user1467267
    Apr 18, 2013 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. Apr 18, 2013 at 13:22

5 Answers 5

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.

7
  • Thanks. Do you know how I can get it out of the localstorage as seperate arrays?
    – nielsv
    Apr 18, 2013 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, 2013 at 15:24
  • @War10ck, Hi, I just stumbled across this and like the idea. Could you have a look at stackoverflow.com/questions/17612962/… and say whether this would be a suitable method please?
    – null
    Jul 12, 2013 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. Sep 24, 2014 at 5: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, 2014 at 14:10
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));
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

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.

1
  • this is a english site. Can you please edit your answer and replace your explanation by an english translation of it?
    – ruud
    Nov 4, 2022 at 7:56
-6
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.