JS checking deep object property existence [duplicate]

There are several possiblities:

Try-catch

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

Fails for:

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;

Fails for:

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

Fails for:

// It's hard(er) to use

function alternative – see comment by @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');

Leave a Comment