JS检查深层对象属性是否存在 [英] JS checking deep object property existence

查看:507
本文介绍了JS检查深层对象属性是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种优雅的方法来检查对象中是否存在某些深层属性。因此,实际上试图避免对未定义的怪异保护性检查。

I'm trying to find an elegant way to check the if certain deep properties exist in an object. So practically trying to avoid monstrous protective checks for undefined eg.

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

我在想的是像

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

任何想法?为方便起见,使用下划线 -library可以解决该问题。

Any ideas? For convenience, the use of underscore-library is ok for the solution.

推荐答案

有几种可能性:

试用

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

失败:

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;

失败:

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

功能

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

失败:

// It's hard(er) to use

功能替代 - 请参阅@Olical的评论

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');

这篇关于JS检查深层对象属性是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆