How to create a hash or dictionary object in JavaScript

Saurabh Kumar picture Saurabh Kumar · Jun 9, 2011 · Viewed 256k times · Source

I want to create a map object in javascript. I came to the following idea:

 var a = new Array();
 a["key1"] = "value1";
 a["key2"] = "value2";

but then how I can find if a particular key exists or not?

Answer

Quentin picture Quentin · Jun 9, 2011

Don't use an array if you want named keys, use a plain object.

var a = {};
a["key1"] = "value1";
a["key2"] = "value2";

Then:

if ("key1" in a) {
   // something
} else {
   // something else 
}