How to create a hash or dictionary object in JavaScript
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) ...
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
}
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:
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
- MDN Documentation: Map, Symbol, Set, WeakMap, WeakSet