Friday, May 4, 2012

How to create a simple map using JavaScript/JQuery


How can you create the JavaScript/JQuery equivalent of this Java code:




Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times

function Object get(k) {
return map.get(k);
}


Source: Tips4all

5 comments:

  1. var map = new Object();
    map[myKey1] = myObj1;
    map[myKey2] = myObj2;

    function get(k) {
    return map[k];
    }

    //map[myKey1] == get(myKey1);

    ReplyDelete
  2. Just use plain objects:

    var map = {"key1":"value1","key2":"value2"}
    function get(k){
    return map[k];
    }

    ReplyDelete
  3. var map = {'myKey1':myObj1, 'mykey2':myObj2};
    // You don't need any get function
    // just use
    // map[[mykey1]

    ReplyDelete
  4. If you're not restricted to JQuery, you can use the prototype.js framework. It has a class called Hash: You can even use JQuery & prototype.js together. Just type jQuery.noConflict();

    var h = new Hash();
    h.set("key", "value");
    h.get("key");
    h.keys(); // returns an array of keys
    h.values(); // returns an array of values

    ReplyDelete
  5. var oa_data = new java.util.HashMap();
    //Repeat as many times as required to the key/value pairs
    oa_data.put("MasterID","aabbcc");


    works for me

    ReplyDelete