Slopeside Creative Slopeside Creative - 4 years ago 222
Javascript Question

check if object property exists - using a variable

checking for existence of javascript object property with a variable as part of the object name.

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 when i want it to check for myObj.prop

Answer Source
if(myObj.hasOwnProperty("<property name>")){
    alert("yes, i have that property");
}

Or

if("<property name>" in myObj) {
    alert("yes, i have that property");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download