Can you guys help me make a shorthand function determining whether an object property exists? In 99% of the cases I want to use it to check whether the returned json object contains the specified property or not. Note that there is no guarantee that any of the parent properties or even the json object itself must be defined.
I was thinking of something in this manner:
function propertyExists(<property>) {
// property is something like data.property.property
return typeof(data) !== "undefined" && typeof(data.property) !== "undefined" && typeof(data.property.property) !== "undefined";
}
I don’t know how to write it in a dynamic manner to check all the parent properties. Also the in-parameter should be just a reference to the “data.property.property” and not a string, so I don’t know how to find the parent properties within that either.
Here’s a function I have lying around from a project that tells you if a property is defined (including all of its parent properties, if any):
It’s supposed to be used like this:
You can easily tweak this to return the value itself (or
null) instead oftrue/false.Update: After reading the comments on the question, I googled the Javascript
inoperator and replaced thetypeoftest with that. Now the code is written “how it was meant to be”.