How to store an array of objects in Local Storage?

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.

Leave a Comment