Skip to content Skip to sidebar Skip to footer

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 v

Solution 1:

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.


Solution 2:

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"]); 

Solution 3:

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


Post a Comment for "How To Store An Array Of Objects In Local Storage?"