Question

I know localstorage is just a simple hash map with getItem and setItem. What if my Item is a JSON array and I would just like to add one item at the end of the array? Are there more efficient ways than calling setItem for just one more entry?

Was it helpful?

Solution

Unfortunately no.

localStorage support only the string type so you will have to JSON.stringify the array before saving, which means you need to load it and parse it before you can add anything to it.

You can write a simple wrapper to do this (can support various types):

function appendItem(key, data) {

    var t = data.constructor, tmp;

    switch(t) {

         case Array:
             tmp = localStorage.getItem(key);
             tmp = (tmp === null) ? [] : JSON.parse(tmp);
             tmp.push(data);

             localStorage.setItem(key, JSON.stringify(tmp));
             break;

         case String:
             //... and so forth
    }
}

(error and same type checking must also be implemented in this approach).

Optionally you can use a delayed writing approach so you can fill the array more efficiently (burst writing) and only when needed the data is updated to localStorage. Here you can initially load the existing array and then update it when data is added to it.

You can bake this into an object for each array, but for simplicity:

var a = []; //load existing array at init
var timer;
var key = 'myArray';

//append data to array and re-start timer
function appendArray(item) {

    clearTimeout(timer);
    a.push(item);

    timer = setTimout(writeData, 2000); //wait 2 seconds to write last append(s)
}

//write the data if dirty
function writeData() {
    localStorage.setItem(key, JSON.stringify(a));
}

For security you can subscribe to the window.onunload event to do a final write when user navigates away from current page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top