如何在本地存储中存储对象数组? [英] How to store an array of objects in Local Storage?
问题描述
这是我的代码.几天以来,我一直在尝试创建一个对象数组,然后将其存储在本地存储中.问题来了,我需要先从本地存储中获取现有值.
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.
推荐答案
该代码的问题是:
您将得到的结果包装在一个数组中,但理论上,您希望已经拥有一个数组.
您存储的是 (您通过编辑删除了它.)user
,而不是 get
或 abc
.
要存储数组,请执行以下操作:
To store the array, do what you're doing:
localStorage.setItem("users", JSON.stringify(users));
获取数组:
users = JSON.parse(localStorage.getItem("users") || "[]");
请注意,如果 getItem
返回 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"});
<小时>
示例(在 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.
这篇关于如何在本地存储中存储对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!