Object has-property-deep check in JavaScript

后端 未结 8 2094
走了就别回头了
走了就别回头了 2020-12-01 21:16

Let\'s say we have this JavaScript object:

var object = {
   innerObject:{
       deepObject:{
           value:\'Here am I\'
       }
   }
};
<
8条回答
  •  情话喂你
    2020-12-01 21:52

    You could make a recursive method to do this.

    The method would iterate (recursively) on all 'object' properties of the object you pass in and return true as soon as it finds one that contains the property you pass in. If no object contains such property, it returns 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

提交回复
热议问题