Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you test if an object has a specific property?

How can you test if an object has a specific property?

Appreciate I can do ...

$members = Get-Member -InputObject $myobject  

and then foreach through the $members, but is there a function to test if the object has a specific property?

Additional Info: The issue is I'm importing two different sorts of CSV file, one with two columns, the other with three. I couldn't get the check to work with "Property", only with "NoteProperty" ... whatever the difference is

if ( ($member.MemberType -eq "NoteProperty" ) -and ($member.Name -eq $propertyName) )  
like image 722
SteveC Avatar asked Nov 18 '14 15:11

SteveC


People also ask

How can you tell if an object has a specific property?

The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.

How do you check if an object has a property in 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.

How do you check if an object has any properties in JavaScript?

You can use the built in Object. keys method to get a list of keys on an object and test its length.


Video Answer


2 Answers

Like this?

 [bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest") 
like image 180
CB. Avatar answered Sep 20 '22 23:09

CB.


You can use Get-Member

if(Get-Member -inputobject $var -name "Property" -Membertype Properties){ #Property exists } 
like image 21
Paul Avatar answered Sep 18 '22 23:09

Paul