Sunday, August 21, 2011

Creating a Map like data structure in java script

While I was working in one of my projects (GSoC 2011 - Sakai CLE mobile app) I wanted to have a map like data structure in java. Just for the clarity I will explain my scenario:

I have a list of items that I am being iterated over it and doing some stuff. So what I wanted is to have store some dynamic values on the fly as key:value pairs. I am actually new to Java Script and I am not sure this a good way and I appreciate if anyone can share any other possible ways. Here is what I did:

var map = new Object();
for ( var i = 0; i < data.length; i++) {
//what ever your logic goes here
map[data[i].key] = {val: data[i].value}; //map keys to values
console.log(data[i].key + ": " + (map[data[i].key]).val);
}
view raw mapexample.js hosted with ❤ by GitHub


Output:

key1: val1
key2: val2
.
.
keyn: valn

Correct me if this is wrong or not the efficient way!

No comments:

Post a Comment