Append data to localStorage object

后端 未结 4 735
夕颜
夕颜 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:42

    You are using Object.assign() wrong. See here for info about it.

    Do you really need newStudent2 to be an array of a single object? If not you can simply do stored.push(newStudent2), where newStudent2 is an object and not an array with a single object.

    So, something like:

    var students = [];
    
    // add the first student
    // Notice how the student is now an object and not an array containing an object.
    var newStudent = {
         "name":        "John",
         "age":         21,
         "nationality": "Spanish"
     };
    
    students.push(newStudent);
    
    localStorage.setItem("students", JSON.stringify(students));
    
    
    // Retrieve the object from storage to add a new student
    var retrievedObject = localStorage.getItem("students");
    var stored          = JSON.parse(retrievedObject);
    
    // add a new student
    // Notice how the student is now an object and not an array containing an object.
    var newStudent2 = {
        "name":        "Mary",
        "age":         20,
        "nationality": "German"
    };
    
    stored.push(newStudent2);
    
    // Update the storage
    localStorage.setItem("students", JSON.stringify(stored));
    var result = localStorage.getItem("students");
    
    console.log(result);
    

提交回复
热议问题