简体   繁体   中英

How to add/append to existing Web storage in javascript?

I am trying to add/append to new/existing localStorage using this code:

 function add(){

    var name = document.getElementById("name").value;
    var ort = document.getElementById("ort").value;

    var user = {"name":name, "ort":ort};

    var exist = [];

    var tmp = (JSON.parse(localStorage.getItem("users")));

    if(tmp)
        exist.push(tmp);
    exist.push(user);
    localStorage.setItem("users",JSON.stringify(exist));

    console.log(JSON.parse(localStorage.getItem("users")));
    var obj = JSON.parse(localStorage.getItem("users"));
    for(var i=0; i<obj.length; i++) {
        console.log('key: ' + i + '\n' + 'value: ' + obj[i]);
    }


}

Looking into Chrome developer tools localStorage looks like this:

   [[{"name":"a","city":"a"}],{"name":"b","city":"b"}]

But what I want is:

   [{"name":"a","city":"a"},{"name":"b","city":"b"}]

What am I doing wrong?

Any help appreciated,

Best regards,

localStorage only store strings . You need to stringify your exist and then save it to storage

localStorage.setItem("users",JSON.stringify(exist));

To retrieve it use JSON.parse

var exist = JSON.parse(localStorage.exist); //Even for users object do the same

Update

To only push the objects inside the array tmp to exist use map() :

tmp.map(function(item){
 exist.push(item);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM