Search code examples
javascriptgoogle-chrome-extension

How to stock array with localStorage (Chrome Extension)?


I tried to stock an array in localStorage but then I read it was impossible. So I tried that:

    array = {};
    array.name =        $('[name="name"]').val();
    array.username =    $('[name="username"]').val();
    array.password =    $('[name="password"]').val();
    
    alert(localStorage['accounts']);
    local = JSON.parse(localStorage['accounts']);
    localu = local.push(array);
    alert(JSON.stringify(localu));

In fact the scripts stops at the first alert which returns '[]' (I previously put that value to check the result).

Why isn't my script working?


Solution

  • JavaScript, {} is an Object. [] is an Array.

    var array = [] and var array = new Array() do the same thing.

    An array is an ordered container of stuff, each value has an index not a key.

    An object is a named container of stuff, each "stuff" has a key.

    Your array is definitely an object.

    var data = {};
    data.name =        $('[name="name"]').val();
    data.username =    $('[name="username"]').val();
    data.password =    $('[name="password"]').val();
    
    alert(localStorage['accounts']);
    // > undefined OR the value
    local = JSON.parse(localStorage['accounts']);
    // local contains a parsed version of localStorage['accounts']
    localu = local.push(array);
    // localu = 0 (push returns the length i think?)
    alert(JSON.stringify(localu));
    

    Try the following. I've not tested it, but might work.

    var data = {};
    data.name =        $('[name="name"]').val();
    data.username =    $('[name="username"]').val();
    data.password =    $('[name="password"]').val();
    
    if (localStorage['accounts'] == undefined) { // fixed
    // does the key exist? No so create something to get us started
       localu = { accounts: [] };
    } else {
    // the key exists! lets parse it
       localu = JSON.parse(localStorage['accounts']);
    }
    // add the new "data" to the list
    localu.accounts.push(data);
    // save the results (we have to stringify it)
    localStorage['accounts'] = JSON.stringify(localu);