46

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.

Floern
  • 33,559
  • 24
  • 104
  • 119
Juggernaut
  • 766
  • 1
  • 10
  • 15
  • 2
    And what is the problem? What is the error you're getting? – Turtle May 03 '17 at 14:07
  • When onRegisterSubmit is executed, this become the structure. [[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}] – Juggernaut May 03 '17 at 14:10
  • Possible duplicate of [Storing Objects in HTML5 localStorage](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – xale94 May 03 '17 at 14:12
  • Yes but I hardly understood the replies. I did try them. What are my mistakes. – Juggernaut May 03 '17 at 14:14

3 Answers3

92

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Neha: Good deal. The main points above are still valid, though. Added an example. – T.J. Crowder May 03 '17 at 14:17
  • @T.J.Crowder Thank you. I have a question; can be added but how can a user be removed? –  Oct 21 '20 at 09:01
  • @Emre6 - Do the same thing, but in the middle instead of `users.push(user);` do `users = users.filter(u => u.id === userIdToRemove);` or similar. :-) – T.J. Crowder Oct 21 '20 at 09:14
  • Thank you for your answer. Could you please show me where I went wrong? https://jsfiddle.net/emresaracoglu/9qjL1gho/5/ –  Oct 21 '20 at 09:55
  • @Emre6 - You didn't, I have a typo in my comment above, it should be `!==` instead of `===`. With `filter`, you specify what items to **keep**. So if we want to remove the item with the ID `userIdToRemove`, we need `.filter(u => u.id !== userIdToRemove)`. :-) – T.J. Crowder Oct 21 '20 at 09:59
6

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"]); 
Suresh B
  • 1,658
  • 1
  • 17
  • 35
4

See this post.

You can't store Objects, you have to store a String. So the workaround is to stringify your Object before you store it (for example, you could use change it to a JSON object, store it, and read it again when needed).

Community
  • 1
  • 1
Turtle
  • 1,626
  • 16
  • 26
  • When you downvote an answer, please post a comment explaining why you downvoted it, as it serves few purpose otherwise. – Turtle May 04 '17 at 09:50
  • Your answer is correct though, I did just that and that is how I did it. I did an up-vote, no idea why someone gave a down vote. – Juggernaut May 05 '17 at 06:34