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
If you can use lodash
library, it has a very elegant solution, hasIn.
_.hasIn(someObject, 'member.level1.level2.level3');
for example,
var obj = {'x': 999, 'a': {'b': {'c': 123, 'd': 234}}}
// => undefined
_.hasIn(obj, 'x')
// => true
_.hasIn(obj, 'a.b.d')
// => true
_.hasIn(obj, 'a.b.e')
// => false
In general, you can use if(property in object)
, but this would be still cumbersome for nested members.
You could write a function:
function test(obj, prop) {
var parts = prop.split('.');
for(var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if(obj !== null && typeof obj === "object" && part in obj) {
obj = obj[part];
}
else {
return false;
}
}
return true;
}
test(someObject, 'member.member.member.value');
DEMO