views:

107

answers:

4

Is there any way to create Map data structure like java in java script?

+1  A: 

http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent

Charlie Collins
That answer deals with `HashMap`, but that's not what Suvonkar asked about. In Java, a `Map` data structure is a set of key/value pairs, `HashMap` is a specific type of this that stores them in a special way for faster lookups.
R. Bemrose
Please post dup links in comments, not as standalone answers.
Paul Sasik
@R - Yes, Suvonkar said Map, but he also said "like in Java." In Java the vast majority of map implementations are based on HashMap, so I thought that article might be helpful. @Paul - Thanks for the tip, I will do that from now on, I did not know that's how it should have been handled.
Charlie Collins
+2  A: 

Yes, you can create a JS object and use properties as keys. E.g.

var map = {};
map.key1 = 'value1';
map.key2 = 'value2';
map['key3'] = 'value3';

alert(map.key1); // value1
alert(map['key2']); // value2
var key = 'key3';
alert(map[key]); // value3

It has much similarities with Javabeans and EL, if you know Java/JSP well.

BalusC
A: 

You could just create a named array.

var map = []; // Note that the brackets here are different than in Balus's answer
map['key1'] = 'value1';
map['key2'] = 'value2';
map['key3'] = 'value3';

alert(map['key1']);
alert(map['key2']);
var key = 'key3';
alert(map[key]);

I haven't compared the overhead of this as opposed to using a JavaScript object. I just assume it would be lower.

R. Bemrose
The overhead should be the same, since an array in JavaScript is just an object that treats numeric keys a little differently.
Matthew Crumley
There is no benefit in using an Array rather than an object here: you're not using any of Array's unique features, and there's not reason at all why it would be faster.
Tim Down
A: 

Unlike normal JavaScript objects, my jshashtable allows arbitrary keys and has a very similar API to Java's HashMap.

Tim Down
Why did you downvote all the other answers? Is it already Friday?
BalusC
BalusC: I didn't downvote all the other answers. I only downvoted R. Bemrose's answer, which was because it copied yours and added nothing valuable.
Tim Down
Ah okay. It was just striking me that any answer expect yours was downvoted for no clear reason.
BalusC
Possibly mine escaped downvote by not existing when all the others were downvoted.
Tim Down