How do I check if an object has a property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
How do I check if an object has a property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
You need to use the method
object.hasOwnProperty(property)
. It returns true if the object has the property and false if the object doesn't.For testing simple objects use:
if (obj[x] !== undefined)
If you don't know what object type it is use:
if (obj.hasOwnProperty(x))
All other options are slower..
Details
Performance evaluation of 100,000,000 cycles under Nodejs to the 5 options suggested by others here:
The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:
if (X in Obj)...
It is between 2 to 6 times slower depending on the use caseBottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use 'if (obj.hasOwnProperty(x))...'.
Otherwise, when using a simple object and not being worried about the object's prototype chain, using
if (typeof(obj[x]) !== 'undefined')...
is the safest and fastest way.If you use a simple object as a hash table and never do anything kinky, I would use
if (obj[x])...
as I find it much more readable.Have fun.
Do not do this
object.hasOwnProperty(key))
, its really bad because these methods may be shadowed by properties on the object in question - consider{ hasOwnProperty: false }
- or, the object may be a null object(Object.create(null))
.The best way is to do
Object.prototype.hasOwnProperty.call(object, key)
or:OK, it looks like I had the right answer unless if you don't want inherited properties:
Here are some other options to include inherited properties:
hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain."
So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself,.
If you want to determine if the property exists in the prototype chain you main want to use in, like:
I hope this helps.
i used this. which is lots helped me if you have a objects inside object