LocalStorage保存和加载JS对象 [英] LocalStorage save and load JS Object
问题描述
我正在尝试通过localStorage保存一个由多个JS对象组成的数组.
I'm trying to save an array consisting of multiple JS objects via localStorage.
I guess I'm having the same trouble as Fail when pushing an array of js objects to localStorage and then retrieving it and parsing, but there's no solution to it.
var featureArray=[];
map.on('click', function(evt) {
if (feature) {
featureArray.push(feature.values_);
}
});
function saveFeatures() {
localStorage.setItem('features', featureArray);
}
saveFeatures();
当我尝试通过localStorage.getItem('features')
加载它们时,输出类似于:
when I try to load them via localStorage.getItem('features')
the output is something like:
[对象对象],[对象对象]
[object Object],[object Object]
但是我实际上希望保存此结构背后的值.
But I actually want the values behind this structure to be saved.
我尝试了localStorage.setItem('features', JSON.stringify(featureArray))
,但是抛出了错误
I tried localStorage.setItem('features', JSON.stringify(featureArray))
, but that throws the error
TypeError:将圆形结构转换为JSON
TypeError: Converting circular structure to JSON
我在做什么错了?
console.log(featureArray)的输出:
console.log(featureArray)'s output:
(2) [{…}, {…}]
0:
geometry:ol.geom.MultiPolygon {pendingRemovals_: {…}, dispatching_: {…}, listeners_: {…}, revision_: 2, ol_uid: 39, …}
krs:"Niedersachsen"
sumarea_1_2014:20298
sumarea_1_2015:16045
sumarea_1_2016:19008
sumarea_3_2014:3888
sumarea_3_2015:27971
sumarea_3_2016:15520
sumarea_5_2014:11888
sumarea_5_2015:14671
sumarea_5_2016:31307
__proto__:Object
1:
geometry:ol.geom.MultiPolygon {pendingRemovals_: {…}, dispatching_: {…}, listeners_: {…}, revision_: 2, ol_uid: 41, …}
krs:"Nordrhein-Westfalen"
sumarea_1_2014:23100
sumarea_1_2015:2399
sumarea_1_2016:21916
sumarea_3_2014:11375
sumarea_3_2015:31563
sumarea_3_2016:20300
sumarea_5_2014:859
sumarea_5_2015:20633
sumarea_5_2016:31101
__proto__:Object
length:2
__proto__:Array(0)
更新: https://jsfiddle.net/ytc26fju/3/ .将鼠标悬停在点上以更新数组.然后点击保存,然后点击加载按钮.
UPDATE: https://jsfiddle.net/ytc26fju/3/ . hover over the dot to update the array. then click save and then the load button.
推荐答案
JSON.stringify
accepts an replacer parameter which will help you get rid of cyclic object while stringifying your object.
这是一个非常简单的实现,它将循环对象的第二次出现转换为null
:
Here is a really simple implementation which will convert the second occurrence of a cyclic object to null
:
function cyclicsCleaner() {
var seenObjects = [];
return function cleanCyclics(key, obj) {
if (obj && typeof obj === 'object') {
if (seenObjects.indexOf(obj) !== -1) {
return null;
}
seenObjects.push(obj);
}
return obj;
}
}
// generate a cyclic object
var a = {};
var b = {
cyclic: a
};
a.b = b;
console.log(JSON.stringify(a, cyclicsCleaner()));
这篇关于LocalStorage保存和加载JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!