JavaScript check if property is defined

What is the recommended way to check if an object property is defined, such as obj.prop.otherprop.another?

if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another) 

it works well, but ugly enough.

+6
source share
3 answers

The most efficient way to do this is to check the obj.prop.otherprop.another object in the try {} catch (exception) {} block. This would be the fastest if everyone else existed; otherwise the exception will be handled.

 var a = null; try { a = obj.prop.otherprop.another; } catch(e) { obj = obj || {}; obj.prop = obj.prop || {}; obj.prop.otherprop = obj.prop.otherprop || {}; obj.prop.otherprop.another = {}; a = obj.prop.otherprop.another ; } 
+3
source

Not to say it's better, but ...

 x = null try { x = obj.prop.otherprop.another; } catch() {} // ... 

Or alternatively ...

 function resolve(obj, path) { path = path.split('.'); while (path.length && obj) obj = obj[path.shift()]; return obj; } x = resolve(obj, 'prop.otherprop.another'); 

... but I think the actual answer is that there is no best practice for this. Not that I knew.

0
source

If you're in a wacky mood, this will work:

 if ((((obj || {}).prop || {}).anotherprop || {}).another) { ... } 

But I don’t know if the initialization of three new objects really is not worth repeatedly typing the path.

0
source

All Articles