Is there a simpler way than using ___ in object
to check the existence of each level of an object to check the existence of a single member?
More conci
Something like (warning: untested code ahead)
var testProperty = function(obj, proplist) {
for (var i=0; i < proplist.length; i++) {
if (obj.hasOwnProperty(proplist[i])) {
obj = obj[proplist[i]];
} else {
return false;
}
}
return true;
}
Here's one way: http://jsfiddle.net/9McHq/
var result = ((((someObject || {}).member || {}).member || {}).member || {}).value;
alert( result );
You could also try/catch TypeError?
try {
console.log(someObject.member.member.member.value);
} catch(e) {
if (e instanceof TypeError) {
console.log("Couldn't access someObject.member.member.member.value");
console.log(someObject);
}
}
Check out lodash-deep’s deepHas
https://github.com/marklagendijk/lodash-deep#_deephascollection-propertypath
And this too https://github.com/danielstjules/hoops
if (someObject.member && someObject.member.member &&
someObject.member.member.member && someObject.member.member.member.value) ...
or similarly:
var val = foo.bar && foo.bar.jim && foo.bar.jim.jam && foo.bar.jim.jam.value;
This will not 'work' if any particular value happens to be null
, false
, 0
, or ""
(an empty string), but with the possible exception of the final value, this seems unlikely to be the case.
Also, note that typeof ____ !== "undefined"
is not the correct test to see if an object has a property. Instead you should use ___ in object
, e.g. if ("member" in someObject)
. This is because you can set a property to an explicit value of undefined
, which is different from removing it with delete someObject.member
.
Theres a safeRead function defined here on thecodeabode which allows a safeRead of nested properties i.e.
safeRead(foo, 'bar', 'jim', 'jam');
if any of the properties are null or undefined a blank string is returned - useful for formatting / string interpolation