Javascript 如何在本地存储中存储对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43762363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store an array of objects in Local Storage?
提问by Juggernaut
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.
这是我的代码。几天以来,我一直在尝试创建一个对象数组,然后将其存储在本地存储中。问题来了,我需要首先从本地存储中获取现有值。
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.
我已经尝试了几天,任何帮助将不胜感激。
回答by T.J. Crowder
The issues with that code are:
该代码的问题是:
You're wrapping the result you get in an array, but in theory, you want to alreadyhave an array.
You're storing(You removed that with an edit.)user, notgetorabc.
您将获得的结果包装在一个数组中,但理论上,您希望已经拥有一个数组。
您正在存储(您通过编辑删除了它。)user,而不是get或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 getItemreturns nullbecause we've never stored our users there.
请注意它如何提供默认值(空数组) ifgetItem返回,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]):
示例(在 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.
这会向您显示控制台中的当前用户列表,每次刷新页面时都会添加一个。
回答by Nathan
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 对象、存储它并在需要时再次读取它)。
回答by Suresh B
Try something like this:- link https://jsfiddle.net/sureshraina/nLexkyfw/1/
尝试这样的事情: - 链接https://jsfiddle.net/sureshrina/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"]);

