Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append data to localStorage object

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);
like image 794
McRui Avatar asked Mar 12 '16 21:03

McRui


People also ask

Can localStorage store objects?

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.

Can you modify localStorage?

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.

How can I store multiple values inside one localStorage key?

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.

How do I add an array to 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.


1 Answers

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);
like image 74
Sergey Yarotskiy Avatar answered Oct 12 '22 15:10

Sergey Yarotskiy