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.

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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)?
1

You can use .hasOwnProperty

me.hasOwnProperty('height'); //false

Comments

1

you can use

if (me.hasOwnProperty('height'))
{
 }
else
{
 }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.