3

I am developing a mobile app using JQuery Mobile. Wanted to know whether can i create a HashMap the way we can do it in JAVA, in JQuery Mobile?

If yes, then how? please if possible provide me some example.

Prals
  • 606
  • 2
  • 7
  • 22
  • JS Objects are similar to Associative array and are similar to HashMap in Java. Depends whats your requirement. – Subir Kumar Sao Feb 06 '13 at 09:39
  • ON start of application, i would like to take some data from server and save it in key:value format and then as and when required, i will pass in the key to get the respective value. This can called from anywhere in my app. Can this be achieved using Associative Array? – Prals Feb 06 '13 at 09:46

3 Answers3

10

In plain Javascript it is possible to create something very similar to a java HashMap:

var hashmap = {};

Put something in it:

hashmap['key'] = 'value';

Get something out of it:

var value = hashmap['key'];

For most purposes this will do, but it is not exactly the same as a hashmap, see for example this question: JavaScript Hashmap Equivalent

Community
  • 1
  • 1
0

Javascript (EcmaScript 5) currently only has Objects and Arrays. ES Harmony will introduce Maps and Sets, but that's quite a long way until it has wide enough support to effectively use it.

You can use an ordinary Object, in most cases it behaves like a Java-Hashmap.

// initialisation
var o = { key:"value", "another key", 3};
// or
var o = {};
o.key = "value";
// access property
alert(o.key);         // dot-notation
alert(o["key"]);      // bracket notation, same as array[i]
// delete property
delete o.key;

If the key is a valid identifier, you don't need to quote it and also can access it easily with dot-notation, if not (reserved keyword or spaces in it or ...), you need to quote it with either double or single quotes and address it with bracket notation.

Christoph
  • 46,101
  • 18
  • 92
  • 121
0

An easy way to dynamically create a map in JavaScript is to use the following way.

I'm creating a map using an array which contains the id of html elements. In the end, I want to put the html elements ids and values in a key-value pair in a map.

var selectedFilterValuesMap = {};

for (var i = 0; i < filterIdArray.length; i++) {        
    selectedFilterValuesMap[filterIdArray[i].trim()] = $("#"+filterIdArray[i].trim()).val();
}

And, I can access the values in the map like this:

for(var x in selectedFilterValuesMap){
    alert("key - "+x+"\n val - "+selectedFilterValuesMap[x]);
}
Zoran777
  • 510
  • 1
  • 6
  • 25