167

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?

Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

5 Answers5

269

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 
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
43

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

Jeremy
  • 1
  • 85
  • 340
  • 366
  • 1
    you should careful since this is an "experimental technology, part of the ECMAScript 6 (Harmony) proposal" – Ghashange Apr 09 '15 at 11:59
  • someMap.set(key, val) didn't work in nodejs – sports May 04 '15 at 15:44
  • 2
    @sports You're right, Node.js doesn't have many newer features enabled by default (yet!). It is enabled if you set the `node --harmony` flag, and is enabled by default in IO.js. – Jeremy May 04 '15 at 15:49
  • 3
    @Ghashange The proposal has since been standardized, and is supported in current versions of all browsers. :) – Jeremy Aug 13 '15 at 23:10
  • 3
    `Map` on Chrome is painfullt slow, even to get an attribute, and furthermore, as you say, its interface is completely incompatible with normal javascript objects. For example, you can't use `a[key]` and `Object.keys()`. I do not recommend to use it. – Marco Sulla Aug 02 '16 at 09:32
  • It is also not working in IE11. You can check the browser compatibility here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Browser_compatibility – Florian Leitgeb Nov 20 '17 at 13:50
39

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) ...
Robert
  • 21,110
  • 9
  • 55
  • 65
  • 1
    This `Map[key] != null && Map[key] != undefined` is not reliable and should not be used (even more: it's plain wrong). – Tomalak Jun 09 '11 at 19:36
  • 1
    Plain wrong in what sense... It's checking to see if a value is null or undefined, depending on what he wants to do that may help :\... – Robert Jun 09 '11 at 19:39
  • 1
    A value can be both `null` and `undefined`, this does not imply the property does not exist. *Plus* `undefined` can be redefined in JavaScript (try it!), so I would never rely on that. – Tomalak Jun 09 '11 at 21:48
  • 10
    If you redefine `undefined` you deserve any errors it causes. null indicates a deliberate non-value, whereas undefined indicates an uninitialized variable. Just because `null == undefined` will return true, doesn't mean null is exactly the same as undefined. – Robert Jun 09 '11 at 21:56
  • I would never redefine `undefined`. But others might, since nothing keeps them from it. Say I'd create a jQuery plugin for the general public to use, I would not rely on `!= undefined`. Better to use `typeof(val) != "undefined"`. It's just one of those tripwires to fall over. Regarding `!= null` - your wording was *"you can check if the key exists..."* which is exactly what you *can't* with this check. – Tomalak Jun 09 '11 at 22:02
  • `var x = {}; x['key1'] == undefined; // true`. I get your point, that you can assign key1 to the literal value, undefined, but as that means uninitialized I'd still consider that a valid check. I do concede that null does represent an deliberate non-value, which would be proper use of the key and checking for null is not exactly what he wanted and have edited to reflect. – Robert Jun 09 '11 at 22:14
  • 1
    `var x = {}; undefined = true; x.key1 = undefined; x.key1 === undefined; /* true */ x.key1 === true; /* true */ typeof x.key1 === "undefined"; /* false */` – Tomalak Jun 09 '11 at 22:19
  • More to the point: `var x = {}; x['key1'] = undefined; x['key1'] == undefined; // true`. So, would you say that `key1` exists? – Charles Wood Jul 17 '14 at 21:12
1

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

Howard
  • 38,639
  • 9
  • 64
  • 83
0
if( a['desiredKey'] !== undefined )
{
   // it exists
}
KOGI
  • 3,959
  • 2
  • 24
  • 36