Home > Software engineering >  localstorage key numbering breaks when removing an item
localstorage key numbering breaks when removing an item

Time:11-15

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.

CodePudding user response:

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]]);

CodePudding user response:

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

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

}

  • Related