patternjavascriptMinor
Checking for an undefined nested variable in a JS object
Viewed 0 times
checkingundefinednestedforobjectvariable
Problem
Is there a better or shorthand way to perform a check on whether or not a variable within (possibly several levels of) an object is null or undefined?
What I would currently do to check is:
Is there a shorthand way to check for whether or not "json.data.formkeys" is undefined without the concern that one or all of the higher level properties or the object itself might not currently exist?
What I would currently do to check is:
if (typeof json !== 'undefined' || typeof json.data !== 'undefined' || typeof json.data.formkeys !== 'undefined') {}Is there a shorthand way to check for whether or not "json.data.formkeys" is undefined without the concern that one or all of the higher level properties or the object itself might not currently exist?
Solution
There's a lot of ways to do this. Here's an exotic (and costly) one:
As commented, a
A longer and possibly better way to do it is to create a resolver function. Most frameworks I have encountered use some form of this in their getter functions so that getting a value from a half-complete path will just return
if(((json || {}).data || {}).formkeys !== void 0){}As commented, a
try-catch will work// JS has function scope. foo starts its life as declared but undefined
// If the try-catch fails, foo will remain undefined.
try{ var foo = json.data.formkeys; } catch(){}
if(foo !== undefined){}A longer and possibly better way to do it is to create a resolver function. Most frameworks I have encountered use some form of this in their getter functions so that getting a value from a half-complete path will just return
undefined instead of throwing midway.function resolve(path, root){
root = root || window;
return path.split('.').reduce(function(parent, child){
// A quick check for brevity. You can replace this with a better check
// and return logic.
return parent && parent[child];
}, root);
}
var foo = resolve('json.data.formkeys');
if(foo !== undefined){}Code Snippets
if(((json || {}).data || {}).formkeys !== void 0){}// JS has function scope. foo starts its life as declared but undefined
// If the try-catch fails, foo will remain undefined.
try{ var foo = json.data.formkeys; } catch(){}
if(foo !== undefined){}function resolve(path, root){
root = root || window;
return path.split('.').reduce(function(parent, child){
// A quick check for brevity. You can replace this with a better check
// and return logic.
return parent && parent[child];
}, root);
}
var foo = resolve('json.data.formkeys');
if(foo !== undefined){}Context
StackExchange Code Review Q#106752, answer score: 5
Revisions (0)
No revisions yet.