Javascript 在 localStorage 中存储对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42020577/
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
Storing Objects in localStorage
提问by Khushi
I have an array like this:
我有一个这样的数组:
[{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}]
I stored it in localstorageand when I retrieving data from localstorageI got the value:
我将它存储在localstorage,当我从中检索数据时,localstorage我得到了值:
[object, object]
How can I solve this issue?
我该如何解决这个问题?
config.ts
配置文件
import { Injectable } from "@angular/core";
@Injectable()
export class TokenManager {
public tokenKey: string = 'app_token';
constructor() { }
store(content) {
var contentData;
console.log("inside localstorsge store:", content);
contentData = content.map(
(data) => data.name
)
console.log("contentData:", contentData)
localStorage.setItem(this.tokenKey, content);
}
retrieve() {
console.log("inside localstorage");
let storedToken: any = localStorage.getItem(this.tokenKey);
console.log("storedToken:", storedToken);//====> here this console is[object object]
if (!storedToken) throw 'no token found';
return storedToken;
}
}
回答by Curiousdev
local storage limited to handle only string key/value pairs you can do like below using JSON.stringifyand while getting value JSON.parse
本地存储仅限于处理字符串键/值对,您可以在使用JSON.stringify和获取值时执行如下操作JSON.parse
var testObject ={name:"test", time:"Date 2017-02-03T08:38:04.449Z"};
Put the object into storage:
将对象放入存储:
localStorage.setItem('testObject', JSON.stringify(testObject));
Retrieve the object from storage:
从存储中检索对象:
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
回答by Abolfazl Miadian
it is a little late for answering, but I want to answer until future viewers can use it, javascript use objects by reference, then when we store an object to localStorage, in real we store the address of object , not the content of object! then if we want to store object content (absolutely we want), we should do like below:
回答有点晚了,但我想回答,直到未来的观众可以使用它,javascript通过引用使用对象,然后当我们将对象存储到localStorage时,实际上我们存储的是对象的地址,而不是对象的内容!那么如果我们想存储对象内容(绝对是我们想要的),我们应该像下面这样:
store like this:
像这样存储:
localStorage.setItem('my_item', JSON.stringify(my_object));
and use like this:
并像这样使用:
var my_object = JSON.parse(localStorage.getItem('my_item'));
hope to be helpful :)
希望有帮助:)
回答by V_for_Vj
local storage is only capable to handle string key/value pairs. If you want to store json objects use JSON.stringify()and while fetching value from local storage use JSON.parse()
本地存储只能处理字符串键/值对。如果要存储 json 对象,请使用JSON.stringify()并从本地存储中获取值时使用JSON.parse()
Example of object to store:
要存储的对象示例:
var storeObject={name:"TestDate", time:"Date 2020-01-21T08:38:04.449Z"};
way to store:
存储方式:
localStorage.setItem('storeObject', JSON.stringify(storeObject));
way to fetch:
获取方式:
var fetchedObject = localStorage.getItem('storeObject');
console.log('fetchedObject for local storage: ', JSON.parse(fetchedObject ));
回答by Moshiur Rahman
You cannot store something without StringFormat.
如果没有字符串格式,您将无法存储内容。
LocalStoragealways store key and value in string format.
LocalStorage始终以字符串格式存储键和值。
That is why you should convert your data to string whatever it is Arrayor Object.
这就是为什么您应该将数据转换为字符串,无论它是Array还是Object。
To Store data in localStorage first of all stringify it using JSON.stringify()method.
要将数据存储在 localStorage 中,首先使用JSON.stringify()方法对其进行字符串化。
var myObj = [{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}];
localStorage.setItem('item', JSON.stringify(myObj));
Then when you want to retrieve data , you need to parse the String to Object again.
那么当你想要检索数据时,你需要再次将字符串解析为对象。
var getObj = JSON.parse(localStorage.getItem('item'));
回答by Mac
It's easy to store objects in local storage with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.
使用localDataStorage可以轻松地将对象存储在本地存储中,您可以在其中透明地设置/获取以下任何“类型”:数组、布尔值、日期、浮点数、整数、空值、对象或字符串。
[DISCLAIMER] I am the author of the utility [/DISCLAIMER]
[免责声明] 我是该实用程序的作者 [/免责声明]
Examples:
例子:
localDataStorage.set( 'key1', 'Belgian' )
localDataStorage.set( 'key2', 1200.0047 )
localDataStorage.set( 'key3', true )
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } )
localDataStorage.set( 'key5', null )
localDataStorage.get( 'key1' ) --> 'Belgian'
localDataStorage.get( 'key2' ) --> 1200.0047
localDataStorage.get( 'key3' ) --> true
localDataStorage.get( 'key4' ) --> Object {RSK: Array(5)}
localDataStorage.get( 'key5' ) --> null
As you can see, the primitive values are respected. Now, in your case, we would do this:
如您所见,原始值受到尊重。现在,在你的情况下,我们会这样做:
>localDataStorage.set( 'testObject', { name : 'test', time : new Date( '2017-02-03T08:38:04.449Z' ) } )
Note that you can plainly express the object. (All the stringamication is done in the background for you.) When we retreive the key, we get:
请注意,您可以清楚地表达对象。(所有字符串化操作都在后台为您完成。)当我们检索密钥时,我们得到:
>localDataStorage.get( 'testObject' ) -->
>Object {name: "test", time: "2017-02-03T08:38:04.449Z"}

