admin管理员组文章数量:1291135
I need to store a lot of data in local storage for my app. I am successful in storing that. Now i need to fetch data in an array but of the selected key/values and not all or just 1 of them. I have named these key as "section"+id as seen below, need to select these in an array.
I need to store a lot of data in local storage for my app. I am successful in storing that. Now i need to fetch data in an array but of the selected key/values and not all or just 1 of them. I have named these key as "section"+id as seen below, need to select these in an array.
Share Improve this question asked May 14, 2017 at 12:57 user2828442user2828442 2,5257 gold badges66 silver badges120 bronze badges 1- localStorage.getItem(key); – Shiladitya Commented May 15, 2017 at 7:06
2 Answers
Reset to default 9localStorage.getItem(key)
will return the data for the key you provide. Data from localStorage is serialized so you need to parse it with JSON.parse(data)
into a plain JS object and then you can work with it as any other object.
You can only get a single item with localStorage.getItem
so if you want to get multiple items in an array you'll have to loop and get each one individually and put them in an array.
Maybe something like this:
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
return JSON.parse(localStorage.getItem(key));
});
First, we get all the "section###" keys with the filter
function. Then we create a new array with the data for each corresponding item using the map
function.
Try this code. I have edited it.
var keys = [];
var data = [];
for (var key in localStorage) {
if (key.indexOf("section") > -1)
keys.push(key);
}
for (var i in keys) {
data.push(localStorage.getItem(keys[i]))
}
本文标签: javascriptWhat query can i use to fetch data from local storage of selected key valueStack Overflow
版权声明:本文标题:javascript - What query can i use to fetch data from local storage of selected key value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741498538a2381946.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论