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
Add a ment  | 

2 Answers 2

Reset to default 9

localStorage.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