1

I have a an object
me = { name: "Mo", age: 28, } And I want to see if this object has the property "height" for example. (which it doesn't) How can i do this? So for example if it has the property "height" I can give it a value of "5,7".

PLEASE NOTE: I don't want to check for the property VALUE(me.name) but for the property NAME.

Thank you.

zzgooloo
  • 75
  • 3
  • 9

4 Answers4

8

You can use the in operator:

if ("height" in me) {
  // object has a property named "height"
}
else {
  // no property named "height"
}

Note that if the object does not have a property named "height", you can still add such a property:

me.height = 100;

That works whether or not the object had a "height" property previously.

There's also the .hasOwnProperty method inherited from the Object prototype:

if (me.hasOwnProperty("height"))

The difference between that and a test with in is that .hasOwnProperty() only returns true if the property is present and is present as a direct property on the object, and not inherited via its prototype chain.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Than you. Is there a way to print out the property name to the console without the use of a conditional statement? just print out the property name> (and without the use of a for in loop)? – zzgooloo Jul 14 '16 at 21:06
1

You can use .hasOwnProperty

me.hasOwnProperty('height'); //false
Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51
1

Direct Answer:

if (Object.keys(me).indexOf("name") >= 0) {
    //do the stuff
}

BUT, what you should do, is create a contractual object/class/module, expecting me to have the height property. If it doesn't, you should throw an exception. The worst things in programming are half ass expectations. It not only breaks the SOLID precepts but also leads to scenarios like this, where the only solution are repetitive if/switch statements to make sure to treat all possibilities...

Sebas
  • 21,192
  • 9
  • 55
  • 109
1

you can use

if (me.hasOwnProperty('height'))
{
 }
else
{
 }
Joey Etamity
  • 856
  • 4
  • 9