问题描述
这是我的代码。我正在尝试创建一个对象数组,然后我将存储在本地存储中。这是问题,我需要先从本地存储中获取现有值。
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.
然后我需要将新数据对象添加到现有数组中。然后我将其转换为JSON,以便将其存储在本地存储中。
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.
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是这样的对象数组,
I want the JSON to be an array of objects like this,
[{"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}]
我已经尝试了几天,我们将非常感谢任何帮助。
I've been trying for several days and any help will be greatly appreciated.
推荐答案
该代码的问题是:
-
你将结果包装在一个数组中,但理论上,你想已经有一个数组。
(你通过编辑删除了它。)
要存储数组,请执行您正在执行的操作:
To store the array, do what you're doing:
localStorage.setItem("users", JSON.stringify(users));
获取数组:
users = JSON.parse(localStorage.getItem("users") || "[]");
注意如果 getItem $,它如何提供默认值(空数组) c $ c>返回
null
因为我们从未将用户存储在那里。
Note how that provides a default (empty array) if getItem
returns null
because we've never stored our users there.
将用户添加到数组:
users.push({id: 1, foo: "bar"});
示例( [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.
这篇关于如何在Local Storage中存储对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!