Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an array of objects in Local Storage?

This is my code. I am trying since a couple of days to create an Array of Objects, which I will then store in Local Storage. Here is the problem, I need to first Get the existing value from Local Storage.

I then need to add the new data object to the existing array. I then convert it into JSON so that I can store it back in the local storage.

onRegisterSubmit(){     const user = {         a: this.a,         b: this.b,         c: this.c,       id: Date.now()     }         var abc = [];    var get =  JSON.parse(localStorage.getItem('user'));    abc = [get];    abc.push(user);     localStorage.setItem('user', JSON.stringify(abc));     console.log(JSON.stringify(abc));    console.log(get);   } 

I want the JSON to be an array of objects like this,

[{"hour":1,"minute":21,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797882440"},{"hour":1,"minute":24,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797896257"},{"hour":6,"minute":14,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493815470408"}] 

This is my JSON.

[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}] 

I've been trying for several days and any help will be greatly appreciated.

like image 404
Juggernaut Avatar asked May 03 '17 14:05

Juggernaut


People also ask

Can we store objects in localStorage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.


2 Answers

The issues with that code are:

  1. You're wrapping the result you get in an array, but in theory, you want to already have an array.

  2. You're storing user, not get or abc. (You removed that with an edit.)

To store the array, do what you're doing:

localStorage.setItem("users", JSON.stringify(users)); 

To get the array:

users = JSON.parse(localStorage.getItem("users") || "[]"); 

Note how that provides a default (empty array) if getItem returns null because we've never stored our users there.

To add a user to the array:

users.push({id: 1, foo: "bar"}); 

Example (live on jsFiddle [Stack Snippets don't allow local storage]):

(function() { // Scoping function to avoid creating globals     // Loading     var users = JSON.parse(localStorage.getItem("users") || "[]");     console.log("# of users: " + users.length);     users.forEach(function(user, index) {         console.log("[" + index + "]: " + user.id);     });      // Modifying     var user = {         id: Math.floor(Math.random() * 1000000)     };     users.push(user);     console.log("Added user #" + user.id);      // Saving     localStorage.setItem("users", JSON.stringify(users)); })(); 

That shows you the list of current users in the console, adding one each time you refresh the page.

like image 156
T.J. Crowder Avatar answered Sep 20 '22 19:09

T.J. Crowder


Try something like this:- link https://jsfiddle.net/sureshraina/nLexkyfw/1/

var mydatas = new Array();         mydatas[0] = "data";         mydatas[1] = "data1";         mydatas[2] = "data2";          localStorage["mydatas"] = JSON.stringify(mydatas);          var datas = JSON.parse(localStorage["mydatas"]);  
like image 33
Suresh B Avatar answered Sep 19 '22 19:09

Suresh B