[英]How to retrieve multiple keys and values from localStorage
I am storing multiple arrays to localstorage. 我正在将多个数组存储到localstorage。
firstArray = [];
secArray = [];
var firsteobj = {class: class, subject: subject, school: school, area: area, zipcode: zipcode};
firstArray.push(firstobj);
localStorage.firstRecord = JSON.stringify(firstArray);
var secobj = {student: student, grade: grade, age: age};
secArray.push(secobj);
localStorage.secondRecord = JSON.stringify(secArray);
And I am retrieving from the localstorage through the function and download the file. 我正在通过该功能从本地存储中检索并下载文件。
function DownloadRec() {
var a = {};
for (var i = 0; i < localStorage.length; i++) {
var k = localStorage.key(i);
var v = localStorage.getItem(k);
a[k] = v;
//alert(a[k]);
}
let dataUrl = 'data:application/json,' + encodeURIComponent(a[k]);
let exportFileDefaultName = 'test.json';
let linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUrl);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
}
I could see both key(firstRecord,secRocord) and corresponding values to it in the browser. 我可以在浏览器中看到key(firstRecord,secRocord)和对应的值。 I could retrieve only the first key which is localstorage.firstRecord.... I would like to retrieve second key and values which is localstorage.secondRecord also.
我只能检索第一个键,它是localstorage.firstRecord ....我也想检索第二个键和值,它也是localstorage.secondRecord。
Could you please suggest me. 你能建议我吗。
The proper way to set/get localStorage is like this: 设置/获取localStorage的正确方法是这样的:
const myValue = [{ thing: 'myValue' }]
const mySerializedValue = JSON.stringify(myValue)
localStorage.setItem('myKey', mySerializedValue)
localStorage.getItem('myKey')
Also, I noticed "class" being used as a variable name. 另外,我注意到“类”被用作变量名。 Might want to rename because "class" is a keyword in many programming languages, including es6 javascript.
可能要重命名,因为“类”是许多编程语言(包括es6 javascript)中的关键字。
Just create an array of objects like this: 只需创建一个这样的对象数组:
arr=[
obj1:'',
.
.
.
obj2:''
]
and save it in browser using localStorage.setItem('objName') now you can retrieve the whole array.I think this is the best approach in your case. 并使用localStorage.setItem('objName')将其保存在浏览器中,现在您可以检索整个数组。我认为这是您情况下的最佳方法。
You can store multiple values in localstorage using following. 您可以使用以下方法将多个值存储在localstorage中。 Also you can store data in the form of JSON objects as demonstrated:
您还可以按照JSON对象的形式存储数据,如下所示:
//Store Values:
localStorage.setItem('someValue','hello');
let user = {name: 'SomeName', email: 'someemail@gmail.com'};
localStorage.setItem('jsonValue',JSON.stringify(user));
//Retrieve the values from localstorage
let temp = localStorage.getItem('someValue'); //temp is hello
let tempJSONString = localStorage.getItem('jsonValue');
let tempJSON = JSON.parse(tempJSONString );
//tempJSON.name is SomeName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.