How to create a hash or dictionary object in JavaScript [duplicate]

How to create a hash or dictionary object in JavaScript [duplicate]

This question already has an answer here:

JavaScript Hashmap Equivalent

17 answers

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?

Solutions/Answers:

Solution 1:

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 
}

Solution 2:

A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.

Maps do not support the [subscript] notation used by Objects. That syntax implicitly casts the subscript value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key), .set(key, value) and .has(key).

var m = new Map();
var key1 = 'key1';
var key2 = {};
var key3 = {};

m.set(key1, 'value1');
m.set(key2, 'value2');

console.assert(m.has(key2), "m should contain key2.");
console.assert(!m.has(key3), "m should not contain key3.");

Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn’t be able to to distinguish key2 and key3 because their string representations would be the same:

Related:  execute function after complete page load
var o = new Object();
var key1 = 'key1';
var key2 = {};
var key3 = {};

o[key1] = 'value1';
o[key2] = 'value2';

console.assert(o.hasOwnProperty(key2), "o should contain key2.");
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!

Related

Solution 3:

You want to create an Object, not an Array.

Like so,

var Map = {};

Map['key1'] = 'value1';
Map['key2'] = 'value2';

You can check if the key exists in multiple ways:

Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...

Solution 4:

Use the in operator: e.g. "key1" in a.

Solution 5:

if( a['desiredKey'] !== undefined )
{
   // it exists
}