Push JSON Objects to array in localStorage

后端 未结 5 1572
别那么骄傲
别那么骄傲 2020-12-01 03:18

I have a function in Javascript:

var a = [];
function SaveDataToLocalStorage(data)
{       
    var receiveddata = JSON.stringify(data);
    a.push(receivedd         


        
相关标签:
5条回答
  • 2020-12-01 03:23

    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.

    0 讨论(0)
  • 2020-12-01 03:32

    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));
    
    0 讨论(0)
  • 2020-12-01 03:33

    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 讨论(0)
  • 2020-12-01 03:37

    Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.

    An alternative is to use http://rhaboo.org which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:

    var store = Rhaboo.persistent('Some name');
    store.write('count', store.count ? store.count+1 : 1);
    
    store.write('somethingfancy', {
      one: ['man', 'went'],
      2: 'mow',
      went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
    });  
    store.somethingfancy.went[1].mow.write(1, 'lawn');
    

    BTW, I wrote it.

    0 讨论(0)
  • 2020-12-01 03:45
    var arr = [ 'a', 'b', 'c'];
    arr.push('d'); // insert as last item
    
    0 讨论(0)
提交回复
热议问题