Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a Javascript object has a value for a given key? [duplicate]

Possible Duplicate:
How do I check to see if an object has an attribute in Javascript?

I have a Javascript object defined as following:

var mmap = new Object();

mmap['Q'] = 1;
mmap['Z'] = 0;
mmap['L'] = 7;
...

How to check whether this map has a value for a given key (for example 'X')? Does .hasOwnProperty() get into play?

like image 476
Jérôme Verstrynge Avatar asked May 30 '12 19:05

Jérôme Verstrynge


People also ask

How can you tell if an object has a certain key?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do you check if a key has a value in JavaScript?

Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned. Copied! The syntax used with the in operator is: string in object .

Does JavaScript object allow for duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do you know if an object has a key and value?

inObject = function(key, value) { if (this. hasOwnProperty(key) && this[key] === value) { return true }; return false; };


2 Answers

if ('X' in mmap)
{
    // ...
}

Here is an example on JSFiddle.

hasOwnProperty is also valid, but using in is much more painless. The only difference is that in returns prototype properties, whereas hasOwnProperty does not.

like image 134
Kendall Frey Avatar answered Oct 04 '22 07:10

Kendall Frey


You can use:

(mmap['X'] === undefined)

Fiddle: http://jsfiddle.net/eDTrY/

like image 40
Mike Christensen Avatar answered Oct 04 '22 07:10

Mike Christensen