snippetjavascriptCritical
How to check if object property exists with a variable holding the property name?
Viewed 0 times
propertyobjecthowwithholdingchecknameexiststhevariable
Problem
I am checking for the existence of an object property with a variable holding the property name in question.
This is
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.propSolution
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.