If localStorage key is removed, move all next keys by 1 place

101 Views Asked by At

I have this situation where I have localStorage keys

0,1,2,3

and if I delete key 1, in my loops it breaks when it gets to position 1, instead of searching for next 2,3 etc. So my idea is when I delete one key, for example key 1, I want all next keys to move up by one place.

I am working with Angular 1.3.

for (var i = 0; i < localStorage.length; i++) {
    $scope.stored_data.push(ls.get(i));
 }

I am also open for alternative solutions to this problem. As long as I get array with data and loops don't break as they iterate through arrays and localStorage it will do.

1

There are 1 best solutions below

0
Reubend On BEST ANSWER

Here's an alternative way to solve your problem. Instead of storing each value separately, try this:

//Store a list of the values as an array
var list = ["Value 1", "Value 2", "Value 3"];


//Delete the first value of the array, shifting everything forward
list.shift();

//Since local storage only supports strings, we must stringify the array
localStorage["list"] = JSON.stringify(list);

//When it's time to retrieve the list, parse it back to an array from JSON
list = JSON.parse(localStorage["list"]);