6

I have some JSON objects I'd like to store in a map for the lifetime of my app. For example, my app shows a listing of Farms. When a user clicks one of the Farm links, I download a Farm representation as JSON:

Farm 1
Farm 2
...
Farm N

every time the user clicks one of those links, I download the entire Farm object. Instead, I'd like to somehow make a global map of Farms, keyed by their ID. Then when the user clicks one of the above links, I can see if it's already in my map cache and just skip going to the server.

Is there some general map type like this that I could use in jquery?

Thanks

user246114
  • 50,223
  • 42
  • 112
  • 149

3 Answers3

14

What about a JavaScript object?

var map = {};

map["ID1"] = Farm1;
map["ID2"] = Farm2;
...

Basically you only have two data structure in JavaScript: Arrays and objects.

And fortunately objects are so powerful, that you can use them as maps / dictionaries / hash table / associative arrays / however you want to call it.

You can easily test if an ID is already contained by:

if(map["ID3"]) // which will return undefined and hence evaluate to false
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 2
    Actually there is only one data structure in Javascript: the object. In Javascript an "array" is simply an object with numbers as its keys. – ase Jul 16 '10 at 20:59
1

The object type is the closest you'll get to a map/dictionary.

var map={};
map.farm1id=new Farm(); //etc
spender
  • 117,338
  • 33
  • 229
  • 351
0
farmMap = {};
farmMap['Farm1'] = Farm1;
...
R. Hill
  • 3,582
  • 1
  • 20
  • 19