如何在Local Storage中存储对象数组?

时间:2022-05-29 17:11:26

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.

这是我的代码。我正在尝试创建一个对象数组,然后将其存储在本地存储中。这是问题,我需要先从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.

然后我需要将新数据对象添加到现有数组中。然后我将其转换为JSON,以便我可以将其存储在本地存储中。

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,

我希望JSON是这样的对象数组,

[{"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.

这是我的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.

我已经尝试了几天,任何帮助将不胜感激。

3 个解决方案

#1


10  

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

    你是存储用户,而不是获取或abc。 (您通过编辑删除了它。)

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.

请注意,如果getItem返回null,那么它是如何提供默认值(空数组)的,因为我们从未在那里存储过我们的用户。

To add a user to the array:

要将用户添加到阵列:

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

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

示例(live on jsFiddle [Stack Snippets不允许本地存储]):

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

这会显示控制台中当前用户的列表,每次刷新页面时都会添加一个用户。

#2


1  

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

尝试这样的事情: - 链接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"]); 

#3


0  

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

你不能存储对象,你必须存储一个字符串。因此,解决方法是在存储对象之前对其进行字符串化(例如,您可以将其更改为JSON对象,存储它,并在需要时再次读取它)。

#1


10  

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

    你是存储用户,而不是获取或abc。 (您通过编辑删除了它。)

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.

请注意,如果getItem返回null,那么它是如何提供默认值(空数组)的,因为我们从未在那里存储过我们的用户。

To add a user to the array:

要将用户添加到阵列:

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

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

示例(live on jsFiddle [Stack Snippets不允许本地存储]):

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

这会显示控制台中当前用户的列表,每次刷新页面时都会添加一个用户。

#2


1  

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

尝试这样的事情: - 链接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"]); 

#3


0  

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

你不能存储对象,你必须存储一个字符串。因此,解决方法是在存储对象之前对其进行字符串化(例如,您可以将其更改为JSON对象,存储它,并在需要时再次读取它)。