0

I try to remove specific data from localStorage and found this question.

One of the answers seems to use localStorage as an array but I don't have jQuery. To find the specific key (and value) I try to use a for loop:

localStorage.setItem("order", 1);
for(var i=0; i<localStorage.length; i++){ 
    var item=localStorage[i];
    if (item == 'order')  
    {
        alert(item);
        // I want to inspect the value...
        // and then remove it
        localStorage.removeItem(item);
    }
}

This code never alerts and the value order is still there.

What am I missing?

Community
  • 1
  • 1
Noob
  • 3
  • 3

2 Answers2

2

localStorage is an object, you can loop through it like this

localStorage.setItem("order", 1);

for (var attr in localStorage){
   if (attr == 'order') {
       alert(localStorage[attr]);
       localStorage.removeItem(attr);
   }
}

Though there is no reason to loop, as you can simply call

localStorage.removeItem('order');

if you already know the key's name!

baao
  • 71,625
  • 17
  • 143
  • 203
1

To remove a certain key-value-pair from localStorage, use Storage.removeItem() with the correct key:

localStorage.removeItem('order');

There is no need to loop through the items.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94