Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something like a Map<String, Object> I can use to store data in jquery?

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

like image 376
user246114 Avatar asked Jul 16 '10 18:07

user246114


People also ask

Can I map a string in JavaScript?

map() on a string and passed an argument of the function that . map() expects. This works like the . split() method of a string, except that each individual string characters can be modified before being returned in an array.

What is map in jQuery?

The jQuery map() function translates all items in an object or in array to a new array of items. It applies a function to each item of the object or array and maps the results into a new array.

Is map better than object JavaScript?

In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!) In the Map, the original order of elements is preserved. This is not true in case of objects.

Is JavaScript object a map?

In addition, Object in Javascript has built-in prototype. And don't forget, nearly all objects in Javascript are instances of Object, including Map. Therefore, by definition, Object and Map are based on the same concept — using key-value for storing data.


2 Answers

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
like image 117
Felix Kling Avatar answered Sep 18 '22 12:09

Felix Kling


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

var map={};
map.farm1id=new Farm(); //etc
like image 25
spender Avatar answered Sep 21 '22 12:09

spender