views:

38

answers:

1
window.localStorage.setItem("Georgia","Atlanta") 
var x=window.localStorage.getItem("Georgia")

I have a list of 50 states and the largest city stored in localstorage. Using the code above I can easily retrieve that Atlanta is the largest city for "Georgia". Is there an easy way to do a reverse lookup and search for "Atlanta" and get "Georgia"?

+1  A: 

Local Storage is a simple map from key to value, so no. There is no method to look up the key for a value, or more accurately, the key*s* because there may be more than one.

You could additionally store a reverse table of city->state to accomplish this:

// Georgia's largest city is Atlanta
window.localStorage.setItem("Georgia", "Atlanta") 

// What is Georgia's largest city?
var x=window.localStorage.getItem("Georgia") // returns Atlanta

// Atlanta is in Georgia
window.localStorage.setItem("Atlanta", "Georgia")

// What state does Atlanta belong to?
var y=window.localStorage.getItem("Atlanta") // returns Georgia

So now setItem() means "there is a relationship between X and Y" and getItem() means "is there a / what is the relationship between X and Y?"

Ideally you'd have these in two different tables to separate out what type of relationship you're talking about (i.e., state->city and city->state) but you should be okay in this simple case.

Jason Hall