JavaScript中的对象具有属性深层检查 [英] Object has-property-deep check in JavaScript

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

问题描述

假设我们有这个JavaScript对象:

Let's say we have this JavaScript object:

var object = {
   innerObject:{
       deepObject:{
           value:'Here am I'
       }
   }
};

我们如何检查value属性是否存在?

How can we check if value property exists?

我只能看到两种方式:

第一个:

if(object && object.innerObject && object.innerObject.deepObject && object.innerObject.deepObject.value) {
    console.log('We found it!');
}

第二个:

if(object.hasOwnProperty('innerObject') && object.innerObject.hasOwnProperty('deepObject') && object.innerObject.deepObject.hasOwnProperty('value')) {
    console.log('We found it too!');
}

但是有办法进行深入检查吗?假设是这样的:

But is there a way to do a deep check? Let's say, something like:

object['innerObject.deepObject.value']

object.hasOwnProperty('innerObject.deepObject.value')

推荐答案

这种检查没有内置的方法,但是您可以轻松实现它.创建一个函数,传递代表属性路径的字符串,用.分割路径,然后遍历该路径:

There isn't a built-in way for this kind of check, but you can implement it easily. Create a function, pass a string representing the property path, split the path by ., and iterate over this path:

Object.prototype.hasOwnNestedProperty = function(propertyPath) {
  if (!propertyPath)
    return false;

  var properties = propertyPath.split('.');
  var obj = this;

  for (var i = 0; i < properties.length; i++) {
    var prop = properties[i];

    if (!obj || !obj.hasOwnProperty(prop)) {
      return false;
    } else {
      obj = obj[prop];
    }
  }

  return true;
};

// Usage:
var obj = {
  innerObject: {
    deepObject: {
      value: 'Here am I'
    }
  }
}

console.log(obj.hasOwnNestedProperty('innerObject.deepObject.value'));

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

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