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
10 Answers
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.
You can use hasOwnProperty, but based on the reference you need quotes when using this method:
if (myObj.hasOwnProperty('myProp')) { // do something } Another way is to use in operator, but you need quotes here as well:
if ('myProp' in myObj) { // do something } 7Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.
Each of these are variables: appChoice, underI, underObstr.
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){ //enter code here } 2For own property :
var loan = { amount: 150 }; if(Object.prototype.hasOwnProperty.call(loan, "amount")) { //will execute } Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like
var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons' }; To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)
const yoshi = { skulk: true }; const hattori = { sneak: true }; const kuma = { creep: true }; if ("skulk" in yoshi) console.log("Yoshi can skulk"); if (!("sneak" in yoshi)) console.log("Yoshi cannot sneak"); if (!("creep" in yoshi)) console.log("Yoshi cannot creep"); Object.setPrototypeOf(yoshi, hattori); if ("sneak" in yoshi) console.log("Yoshi can now sneak"); if (!("creep" in hattori)) console.log("Hattori cannot creep"); Object.setPrototypeOf(hattori, kuma); if ("creep" in hattori) console.log("Hattori can now creep"); if ("creep" in yoshi) console.log("Yoshi can also creep"); Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...
var loan = { amount: 150 }; loan.installment = undefined; if("installment" in loan) // correct { // will execute } if(typeof loan["installment"] !== "undefined") // incorrect { // will not execute } A much more secure way to check if property exists on the object is to use empty object or object prototype to call hasOwnProperty()
var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons' }; foo.hasOwnProperty('bar'); // always returns false // Use another Object's hasOwnProperty and call it with 'this' set to foo ({}).hasOwnProperty.call(foo, 'bar'); // true // It's also possible to use the hasOwnProperty property from the Object // prototype for this purpose Object.prototype.hasOwnProperty.call(foo, 'bar'); // true Reference from MDN Web Docs - Object.prototype.hasOwnProperty()
2there are much simpler solutions and I don't see any answer to your actual question:
"it's looking for myObj.myProp but I want it to check for myObj.prop"
- to obtain a property value from a variable, use bracket notation.
- to test that property for truthy values, use optional chaining
- to return a boolean, use double-not / bang-bang / (!!)
- use the
inoperator if you are certain you have an object and only want to check for the existence of the property (trueeven if prop value is undefined). or perhaps combine with nullish coalescing operator ?? to avoid errors being thrown.
var nothing = undefined; var obj = {prop:"hello world"} var myProp = "prop"; consolelog( 1,()=> obj.myProp); // obj does not have a "myProp" consolelog( 2,()=> obj[myProp]); // brackets works consolelog( 3,()=> nothing[myProp]); // throws if not an object consolelog( 4,()=> obj?.[myProp]); // optional chaining very nice ⭐️⭐️⭐️⭐️⭐️ consolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwing consolelog( 6,()=> nothing?.[nothing]); // even here it is error-safe consolelog( 7,()=> !!obj?.[myProp]); // double-not yields true consolelog( 8,()=> !!nothing?.[myProp]); // false because undefined consolelog( 9,()=> myProp in obj); // in operator works consolelog(10,()=> myProp in nothing); // throws if not an object consolelog(11,()=> myProp in (nothing ?? {})); // safe from throwing consolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined) // beware of 'hasOwnProperty' pitfalls // it can't detect inherited properties and 'hasOwnProperty' is itself inherited // also comparatively verbose consolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields false consolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined function consolelog(num,myTest){ try{ console.log(num,myTest()); } catch(e){ console.log(num,'throws',e.message); } }You can use hasOwnProperty() as well as in operator.
Several ways to check if an object property exists.
const dog = { name: "Spot" } if (dog.name) console.log("Yay 1"); // Prints. if (dog.sex) console.log("Yay 2"); // Doesn't print. if ("name" in dog) console.log("Yay 3"); // Prints. if ("sex" in dog) console.log("Yay 4"); // Doesn't print. if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints. if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined. Using the new Object.hasOwn method is also an alternative and it's intention is to replace the Object.hasOwnProperty method.
This static method returns true if the specified object has the indicated property as its own property or false if the property is inherited or does not exist on that object.
Please not that you must check the Browser compatibility table carefully before using this in production since it's still considered an experimental technology and is not fully supported yet by all browsers (soon to be though)
var myObj = {}; myObj.myProp = "exists"; if (Object.hasOwn(myObj, 'myProp')){ alert("yes, i have that property"); }Object.hasOwn browser compatibility -
In the answers I didn't see the !! truthiness check.
if (!!myObj.myProp) //Do something 3