How to store an array of objects in Local Storage?

前端 未结 3 1170
迷失自我
迷失自我 2021-01-30 17:44

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 existin

相关标签:
3条回答
  • 2021-01-30 18:29

    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"]); 
    
    0 讨论(0)
  • 2021-01-30 18:36

    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.

    0 讨论(0)
  • 2021-01-30 18:44

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

    0 讨论(0)
提交回复
热议问题