Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 384
Slopeside Creative Avatar asked Jun 14 '12 19:06

Slopeside Creative


People also ask

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


2 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.

like image 161
Rocket Hazmat Avatar answered Oct 09 '22 21:10

Rocket Hazmat


You can use hasOwnProperty, but based on the reference you need quotes when using this method:

if (myObj.hasOwnProperty('myProp')) {     // do something } 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Another way is to use in operator, but you need quotes here as well:

if ('myProp' in myObj) {     // do something } 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

like image 21
Adorjan Princz Avatar answered Oct 09 '22 21:10

Adorjan Princz