user1318194
user1318194

Reputation:

Get ID by key in localStorage

In JS localStorage I can use

localStorage.getItem(key);

to get the value of the entry corresponding to the key in the key variable.

How can I get the entry's ID (instead of value) using the key?


Edit: sorry I must have confused people. What I mean by "key" is the numerical key - which is 0, 1, 2, 3 etc depending on how many items have been saved. Then I want to find out the ID it was stored as, eg foo in the below example, from the numerical key.

localStorage.setItem('foo', 'bar');

Upvotes: 0

Views: 16365

Answers (4)

Lasse Christiansen
Lasse Christiansen

Reputation: 10325

LocalStorage is implemented as a key-value pair ( see for instance: https://developers.google.com/web-toolkit/doc/latest/DevGuideHtml5Storage ) - so you don't have an id like an unique auto-incremented id in a database table.

However, you can access the elements using an index - to get the index of a key in localStorage, the only way I can find is to loop through each key until you find the one you are searching for, like this:

var findIndexOfKey = function(searchKey) {
    for (var i = 0; i < localStorage.length; i++){
        var key = localStorage.key(i);
        if(key === searchKey)
            return i;
    }
    return -1;
}

And then, to retrieve the key using the index, you can do:

localStorage.key(myIndex);

And to retrieve the value, you can do this:

localStorage.getItem(localStorage.key(myIndex));

... or this ( which would be equivalent to localStorage.getItem("myKey")):

localStorage.getItem(localStorage.key(findIndexOfKey("myKey")));

Upvotes: 2

Piotr Krysiak
Piotr Krysiak

Reputation: 2815

I don't think it is possible. Can't you just make localStorage.setItem(yourkey,value)? I mean

localStorage.setItem(0,value)  
localStorage.setItem(1,value)

This may be useful in loops for example.

Upvotes: 0

user1318194
user1318194

Reputation:

The answer:

localStorage.key(key);

Sorry, I realise I've got confused between what's actually called the key, which I called the ID, and it's numerical ID which I called the key...

Upvotes: 0

Sora
Sora

Reputation: 2551

when setting the item you should give it's ID as a value and than when you call getItem(key) it should give it's ID as a return ex:

localStorage.setItem('foo', 'bar');
localStorage.getItem('foo');  // it should return the bar

take a look for this examples it may help : http://mathiasbynens.be/notes/localstorage-pattern

Upvotes: 0

Related Questions