HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to check if object property exists with a variable holding the property name?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertyobjecthowwithholdingchecknameexiststhevariable

Problem

I am checking for the existence of an object property with a variable holding the property name in question.

var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";

if(myObj.myProp){
    alert("yes, i have that property");
};


This is undefined because it's looking for myObj.myProp but I want it to check for myObj.prop

Solution

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}


Or

var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}


Or

if('prop' in myObj){
    alert("yes, i have that property");
}


Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.

Code Snippets

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}
var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}
if('prop' in myObj){
    alert("yes, i have that property");
}

Context

Stack Overflow Q#11040472, score: 1596

Revisions (0)

No revisions yet.