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?
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.
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 .
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
inObject = function(key, value) { if (this. hasOwnProperty(key) && this[key] === value) { return true }; return false; };
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.
You can use:
(mmap['X'] === undefined)
Fiddle: http://jsfiddle.net/eDTrY/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With