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

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

我希望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"}]

这是我的JSON.

[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}]

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

该代码的问题是:

>您将结果包装在数组中,但理论上,您希望已经有一个数组.
>您正在存储用户,而不是get或abc. (您通过编辑删除了它.)

要存储数组,请执行您正在执行的操作:

localStorage.setItem("users", JSON.stringify(users));

要获得数组:

users = JSON.parse(localStorage.getItem("users") || "[]");

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

要将用户添加到阵列:

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

示例(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));
})();

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

翻译自:https://stackoverflow.com/questions/43762363/how-to-store-an-array-of-objects-in-local-storage

转载注明原文:javascript – 如何在Local Storage中存储对象数组?