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
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.
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.
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.
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.
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
The object type is the closest you'll get to a map/dictionary.
var map={};
map.farm1id=new Farm(); //etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With