JS check object existence

I am trying to find an elegant way to check if certain objects exist in an object. Therefore, they practically try to avoid monstrous security checks for undefined for example.

if ((typeof error !== 'undefined') && (typeof error.responseJSON !== 'undefined') && (typeof error.responseJSON.error) && (typeof error.responseJSON.error.message)) { errorMessage = error.responseJSON.error.message; } 

What I'm thinking of is a handy feature like

 if (exists(error.responseJSON.error.message)) { ... } 

Any ideas? For convenience, using underscore -library is suitable for the solution.

+7
javascript undefined
source share
2 answers

There are several possibilities:

Try-catch

 try { errorMessage = error.responseJSON.error.message; } catch(e) { /* ignore the error */} 

Failed to complete:

 Object.defineProperty(error, 'responseJSON', { get: function() { throw new Error('This will not be shown') }); 

&&

 errorMessage = error && error.responseJSON && error.responseJSON.error && error.responseJSON.error.message; 

Failed to complete:

 error.responseJSON = 0; // errorMessage === 0 instead of undefined 

function

 function getDeepProperty(obj,propstr) { var prop = propstr.split('.'); for (var i=0; i<prop.length; i++) { if (typeof obj === 'object') obj = obj[prop[i]]; } return obj; } errorMessage = getDeepProperty(error, 'responseJSON.error.message'); // you could put it all in a string, if the object is defined in the window scope 

Failed to complete:

 // It hard(er) to use 

alternative function - see comment from @Olical

 function getDeepProperty(obj) { for (var i=1; i<arguments.length; i++) { if (typeof obj === 'object') obj = obj[arguments[i]]; } return obj; } errorMessage = getDeepProperty(error, 'responseJSON', 'error', 'message'); 
+19
source share

Try underscoring mixin to find a variable using a path. It takes an object and a string and t

 _.mixin({ lookup: function (obj, key) { var type = typeof key; if (type == 'string' || type == "number") key = ("" + key).replace(/\[(.*?)\]/, function (m, key) { //handle case where [1] may occur return '.' + key.replace(/["']/g, ""); //strip quotes }).split('.'); for (var i = 0, l = key.length; i < l; i++) { if (_.has(obj, key[i])) obj = obj[key[i]]; else return undefined; } return obj; } }); 

Now call in your example:

 _.lookup(error, 'responseJSON.error.message') // returns responseJSON.error.message if it exists otherwise `undefined` 
+6
source share

All Articles