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
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))