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?

0

5 Answers 5

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 
}
Sign up to request clarification or add additional context in comments.

7 Comments

How to push a new key later in the "a". Will a.push({"key3","value3"}) work?
push is an array method, and you have a plain object here. There's no restriction on when you can modify the object and you can use the same syntax as in the answer: a["key3"] = "value3";
Syntax could be shortened to var a = {'key1': 'value1', 'key2': 'value2'};
How can i remove the element using key?
@DushyantBangal del a["key1"] or del a.key1
|
42

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

6 Comments

you should careful since this is an "experimental technology, part of the ECMAScript 6 (Harmony) proposal"
someMap.set(key, val) didn't work in nodejs
@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.
@Ghashange The proposal has since been standardized, and is supported in current versions of all browsers. :)
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.
|
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) ...

8 Comments

This Map[key] != null && Map[key] != undefined is not reliable and should not be used (even more: it's plain wrong).
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 :\...
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.
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.
var x = {}; undefined = true; x.key1 = undefined; x.key1 === undefined; /* true */ x.key1 === true; /* true */ typeof x.key1 === "undefined"; /* false */
|
1

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

Comments

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

1 Comment

A key might exist but have an undefined value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.