在 sessionStorage 中保存 Javascript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6193574/
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
Save Javascript objects in sessionStorage
提问by Ferran Basora
SessionStorage and LocalStorage allows to save key/value pairs in a web browser. The value must be a string, and save js objects is not trivial.
SessionStorage 和 LocalStorage 允许在 Web 浏览器中保存键/值对。值必须是字符串,保存js对象不是小事。
var user = {'name':'John'};
sessionStorage.setItem('user', user);
var obj = sessionStorage.user; // obj='[object Object]' Not an object
Nowadays, you can avoid this limitation by serializing objects to JSON, and then deserializing them to recover the objects. But the Storage API always pass through the setItem
and getItem
methods.
现在,您可以通过将对象序列化为 JSON,然后反序列化它们以恢复对象来避免这种限制。但是 Storage API 总是通过setItem
和getItem
方法。
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.getItem('user')); // An object :D
Can I avoid this limitation?
我可以避免这个限制吗?
I just want to execute something like this:
我只想执行这样的事情:
sessionStorage.user.name; // 'John'
sessionStorage.user.name = 'Mary';
sessionStorage.user.name // 'Mary'
I have tried the defineGetter
and defineSetter
methods to intercept the calls but its a tedious job, because I have to define all properties and my target is not to know the future properties.
我已经尝试过defineGetter
和defineSetter
方法来拦截调用,但它是一项乏味的工作,因为我必须定义所有属性,而我的目标是不知道未来的属性。
采纳答案by Ryan Olds
Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.
您可以使用 Web Storage API 提供的访问器,也可以编写包装器/适配器。从您声明的defineGetter/defineSetter 问题来看,听起来像编写包装器/适配器对您来说太多了。
I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.
老实说,我不知道该告诉你什么。也许你可以重新评估你对什么是“荒谬的限制”的看法。Web Storage API 正是它应有的样子,一个键/值存储。
回答by afreeland
Could you not 'stringify' your object...then use sessionStorage.setItem()
to store that string representation of your object...then when you need it sessionStorage.getItem()
and then use $.parseJSON()
to get it back out?
你能不能“字符串化”你的对象......然后sessionStorage.setItem()
用来存储你的对象的字符串表示......然后当你需要它sessionStorage.getItem()
然后用$.parseJSON()
它来取回它?
Working example http://jsfiddle.net/pKXMa/
回答by Ron
The solution is to stringify the object before calling setItem on the sessionStorage.
解决方案是在 sessionStorage 上调用 setItem 之前将对象字符串化。
var user = {'name':'John'};
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.user);
回答by Abdennour TOUMI
This is a dynamic solution which works with all value types including objects :
这是一个动态解决方案,适用于所有值类型,包括对象:
class Session extends Map {
set(id, value) {
if (typeof value === 'object') value = JSON.stringify(value);
sessionStorage.setItem(id, value);
}
get(id) {
const value = sessionStorage.getItem(id);
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
}
Then :
然后 :
const session = new Session();
session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');
回答by Abdennour TOUMI
Use case:
用例:
sesssionStorage.setObj(1,{date:Date.now(),action:'save firstObject'});
sesssionStorage.setObj(2,{date:Date.now(),action:'save 2nd object'});
//Query first object
sesssionStorage.getObj(1)
//Retrieve date created of 2nd object
new Date(sesssionStorage.getObj(1).date)
API
应用程序接口
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
};
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
};
回答by Igor Urisman
Session storage cannot support an arbitrary object because it may contain function literals (read closures) which cannot be reconstructed after a page reload.
会话存储不能支持任意对象,因为它可能包含无法在页面重新加载后重建的函数文字(读取闭包)。
回答by Jijo Paulose
var user = {'name':'John'};
sessionStorage['user'] = JSON.stringify(user);
console.log(sessionStorage['user']);
回答by 3Dos
You could also use the store librarywhich performs it for you with crossbrowser ability.
您还可以使用具有跨浏览器功能的商店库为您执行此操作。
example :
例子 :
// Store current user
store.set('user', { name:'Marcus' })
// Get current user
store.get('user')
// Remove current user
store.remove('user')
// Clear all keys
store.clearAll()
// Loop over all stored values
store.each(function(value, key) {
console.log(key, '==', value)
})
回答by JerryGoyal
You can create 2 wrapper methods for saving and retrieving object from session storage.
您可以创建 2 个包装器方法来从会话存储中保存和检索对象。
function saveSession(obj) {
sessionStorage.setItem("myObj", JSON.stringify(obj));
return true;
}
function getSession() {
var obj = {};
if (typeof sessionStorage.myObj !== "undefined") {
obj = JSON.parse(sessionStorage.myObj);
}
return obj;
}
Use it like this:- Get object, modify some data, and save back.
像这样使用它:- 获取对象,修改一些数据,然后保存回来。
var obj = getSession();
obj.newProperty = "Prod"
saveSession(obj);