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 insight on what I'm doing wrong? Thanks
Here's what I'm trying to do:
// add the first student
var newStudent = [{
"name": "John",
"age": 21,
"nationality": "Spanish"
}];
localStorage.setItem("students", JSON.stringify(newStudent));
// Retrieve the object from storage to add a new student
var retrievedObject = localStorage.getItem("students");
var stored = JSON.parse(retrievedObject);
// add a new student
var newStudent2 = [{
"name": "Mary",
"age": 20,
"nationality": "German"
}];
var stored = Object.assign(stored, newStudent2);
// Update the storage
localStorage.setItem("students", JSON.stringify(stored));
var result = localStorage.getItem("students");
console.log(result);
Local storage can only save strings, so storing objects requires that they be turned into strings using JSON. stringify - you can't ask local storage to store an object directly because it'll store “[object Object]”, which isn't right at all! That also means the object must be run through JSON.
Edit localStorage keys or values View the localStorage key-value pairs of a domain. Double-click a cell in the Key or Value column to edit that key or value.
A single key can only have a single string value in localStorage. You can have multiple keys with different names, or you can do some encoding of the values. For example, you could put all your values in an Array, then encode it using JSON. stringify() and store the result in localStorage.
There are two JSON methods that can help us "store arrays" in localStorage : stringify() - It helps us convert the array into a string. parse() - It allows us to parse the string and construct a JavaScript array.
You should store array, not an object;
var students = [];
var student1 = { s: 1 };
students.push(student1);
localStorage.setItem("students", JSON.stringify(students));
var stored = JSON.parse(localStorage.getItem("students"));
var student2 = { s: 2 };
stored.push(student2);
localStorage.setItem("students", JSON.stringify(stored));
var result = JSON.parse(localStorage.getItem("students"));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With