0

I'm trying to reset my values after having left a this program. Initially the variables were set before departing using setItem. I can read each variable and reset it by using

vartbl[a1,a2,a3,a4,a5.....a50]
itm = localStorage.getItem("a1");
 a1 = JSON.parse(itm);
itm = localStorage.getItem("a2");
 a2 = JSON.parse(itm);**

What I would like is loop to handle this such as

for ( a = 0; a < vartbl.length; a++ ) {
   vartbl[a] = JSON.parse(localStorage.getItem(vartbl[a]))
}

Presently all this does is just put the value vartblp[a] into the indexed position thereby renaming the variable in the array. How can this be done correctly?

Thanks

Abhinav Kumar
  • 2,883
  • 1
  • 17
  • 30
dwt
  • 1
  • 1
  • What's the expected result? Do you want to put the data from localStorage to the `a1`, `a2`, etc variables instead of putting the data into the `vartbl` array? – Finesse Jul 07 '21 at 03:03
  • duplicate of https://stackoverflow.com/questions/17745292/how-to-retrieve-all-localstorage-items-without-knowing-the-keys-in-advance – Ofek Jul 07 '21 at 03:12
  • Does this answer your question? [How to retrieve all localStorage items without knowing the keys in advance?](https://stackoverflow.com/questions/17745292/how-to-retrieve-all-localstorage-items-without-knowing-the-keys-in-advance) – Ofek Jul 07 '21 at 03:12
  • what you want to do after retrieving the value from local storage?, looks like here you are just replacing it. – Rahul R. Jul 08 '21 at 13:07
  • Okay as it turns out i wasn't concise in my description. It turns out the after i reworded my question (while speaking to myself) I was able to find the result I required by looking at question stackoverflow.com/questions/68279475/resetting-all-my-stored-values-to-an-array-using-getitem-javascript This explained why my result wasn't what I had expected. – dwt Jul 09 '21 at 15:32

1 Answers1

0

A loop to fetch the content of localStorage into a variable:

// get all localStorage object keys into an array
var keys = Object.keys(localStorage);
var vartbl = {}

// fill vartbl with the value of localStorage
for (var i in keys) {
    try {
        vartbl[keys[i]] = JSON.parse(localStorage.getItem(keys[i]));
    } catch (e) {
        console.warn(`error parsing ${keys[i]}. Probably not a valid JSON string`,e);
    }
}
Donovan P
  • 591
  • 5
  • 9