0

Don't worry about how it got to be like this, but this is how my localstorage looks:

enter image description here

This is how it should look:

enter image description here

this is how my loop looks:

for(let i=0;i<localStorage.length;i++){
//I do something cool
}

Now imagine that the same numbering error is happening to say 15 values. How can I change either the key column in localstorage so that it starts at 0 and indents by 1 for every value, or my loop so that it runs from the first key to the last key.

phywn8
  • 13
  • 4
  • 1
    Why do you even care if `i` matches or not? You have that `Key` there already. – VLAZ Nov 15 '21 at 09:49
  • How? -> Use an actual array (with `JSON.stringify()` / `JSON.parse()`) – Andreas Nov 15 '21 at 09:49
  • @VLAZ If I doesnt match through the entire loop, the loop either doesn't run for all values, or returns NULL for a missing value. – phywn8 Nov 15 '21 at 09:50
  • @Andreas If I translate localstorage to an array, the key values will still be wrong, no? – phywn8 Nov 15 '21 at 09:52
  • @BalderKun but your screenshot shows you have something called `Key`. It shouldn't matter what `i` is if you just use the `Key` field. What am I missing? – VLAZ Nov 15 '21 at 09:52
  • [Using the Web Storage API - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) – Andreas Nov 15 '21 at 09:54
  • @VLAZ I will add another example – phywn8 Nov 15 '21 at 09:54
  • [How to retrieve all localStorage items without knowing the keys in advance?](https://stackoverflow.com/q/17745292) – VLAZ Nov 15 '21 at 10:04

2 Answers2

0

The localStorage works with key and values. You can loop through it like an javascript object.

for (const [key, value] of Object.entries(localStorage)) {

}

Tonio
  • 1,642
  • 1
  • 4
  • 10
0

You can catch all keys in an array then use that array in your code.

    const lsKeys = Object.keys(localStorage);
    for(let i = 0; i < lsKeys.length; i++) console.log(localStorage[lsKeys[i]]);
Alaa
  • 225
  • 1
  • 4