Append data to localStorage object

后端 未结 4 639
夕颜
夕颜 2021-02-10 11:08

I\'m trying, unsuccessfully, to add a new object to a current localStorage object. Instead of, at the end, having two sets of data in localStorage, I get the last one. Any insig

4条回答
  •  盖世英雄少女心
    2021-02-10 11:47

    You are replacing the stored object by newStudent2 when fetching it back from localStorage:

    var newStudent = [{
         "name":        "John",
         "age":         21,
         "nationality": "Spanish"
     }];
    
    localStorage.setItem("students", JSON.stringify(newStudent));
    
    var retrievedObject = localStorage.getItem("students");
    var stored          = JSON.parse(retrievedObject); <----newStudent1
    
    var newStudent2 = [{
        "name":        "Mary",
        "age":         20,
        "nationality": "German"
    }];
    
    
    var stored = Object.assign(stored, newStudent2); <----Here newStudent1 is replaced by newStudent2
    
    
    localStorage.setItem("students", JSON.stringify(stored)); // Here newStudent2 is replacing old object on localStorage
    var result = localStorage.getItem("students");
    
    console.log(result);
    

    You can instead try creating an array of objects and appending them whenever creating a new one.

    var objects = []
    objects.push(stored) 
    
    localStorage.setItem('students', JSON.stringify(objects))
    

提交回复
热议问题