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