JS对象具有属性深层检查

Bad*_*olt 11 javascript

假设我们有JS对象:

var object = {
   innerObject:{
       deepObject:{
           value:'Here am I'
       }
   }
};
Run Code Online (Sandbox Code Playgroud)

我们如何检查value财产是否存在?我只能看到两种方式:

第一:

if(object && object.innerObject && object.innerObject.deepObject && object.innerObject.deepObject.value) {
    console.log('We found it!');
}
Run Code Online (Sandbox Code Playgroud)

第二个:

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

但有没有办法进行深入检查?让我们说,像:

object['innerObject.deepObject.value']
Run Code Online (Sandbox Code Playgroud)

要么

object.hasOwnProperty('innerObject.deepObject.value')
Run Code Online (Sandbox Code Playgroud)

Vik*_*tev 17

这种检查没有内置方式,但您可以轻松实现.创建一个函数,传递一个表示属性路径的字符串,拆分路径.并遍历此路径:

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'
       }
   }
}

obj.hasOwnNestedProperty('innerObject.deepObject.value');
Run Code Online (Sandbox Code Playgroud)


nem*_*035 12

您可以使用递归方法来执行此操作.

该方法将迭代(递归)您传入的对象的所有"对象"属性,并在true找到包含您传入的属性的属性后立即返回false.如果没有对象包含此类属性,则返回.

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

function hasOwnDeepProperty(obj, prop) {
  if (typeof obj === 'object' && obj !== null) { // only performs property checks on objects (taking care of the corner case for null as well)
    if (obj.hasOwnProperty(prop)) {              // if this object already contains the property, we are done
      return true;
    }
    for (var p in obj) {                         // otherwise iterate on all the properties of this object
      if (obj.hasOwnProperty(p) &&               // and as soon as you find the property you are looking for, return true
          hasOwnDeepProperty(obj[p], prop)) { 
        return true;
      }
    }
  }
  return false;                                  
}

console.log(hasOwnDeepProperty(obj, 'value'));   // true
console.log(hasOwnDeepProperty(obj, 'another')); // false
Run Code Online (Sandbox Code Playgroud)

  • 尽管如此,@ nem还是可以广泛使用的解决方案! (3认同)