Show activity on this post. var a; a = { b: { c: 'd' } }; function isset (fn) { var value; try { value = fn(); } catch (e) { value = undefined; } finally { return value !== undefined; } }; // ES5 console. log( isset(function () { return a.
To check if an object has a nested property, use the optional chaining operator - ?. . The ?. operator allows you to read the value of a nested property without throwing an error if the property does not exist on the object, e.g. obj?.
You can use an utility function like this:
get = function(obj, key) {
return key.split(".").reduce(function(o, x) {
return (typeof o == "undefined" || o === null) ? o : o[x];
}, obj);
}
Usage:
get(user, 'loc.lat') // 50
get(user, 'loc.foo.bar') // undefined
Or, to check only if a property exists, without getting its value:
has = function(obj, key) {
return key.split(".").every(function(x) {
if(typeof obj != "object" || obj === null || ! x in obj)
return false;
obj = obj[x];
return true;
});
}
if(has(user, 'loc.lat')) ...
Well, javascript has try-catch. Depending on what you actually need to do (i.e. what your else
statement would look like if it's undefined
), that may be what you want.
example:
try {
user.loc.lat.doSomething();
} catch(error) {
//report
}
You can combine the checks using lazy and
:
if(user.loc && user.loc.lat) { ...
Or, you use CoffeeScript. And ES2020 has new syntax ( Nullish coalescing Operator ).
user.loc?.lat?. '...'
which would run the checks for loc
property and safeguard against empty objects.
Try this if(user && user.loc && user.loc.lat) {...}
You can check value of null and undefined using typeof
If .loc
has value false
than you can try
if(user && user.loc && typeof(user.loc)!=="undefined"){...}
If you have a huge nested object than have a look at
Source.
function checkNested(obj /*, level1, level2, ... levelN*/) {
var args = Array.prototype.slice.call(arguments),
obj = args.shift();
for (var i = 0; i < args.length; i++) {
if (!obj.hasOwnProperty(args[i])) {
return false;
}
obj = obj[args[i]];
}
return true;
}
var test = {level1:{level2:{level3:'level3'}} };
checkNested(test, 'level1', 'level2', 'level3'); // true
checkNested(test, 'level1', 'level2', 'foo'); // false
Update: Try lodash.get
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With