Object has-property-deep check in JavaScript

后端 未结 8 2045
走了就别回头了
走了就别回头了 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:55

    Alternative recursive function:

    Loops over all object keys. For any key it checks if it is an object, and if so, calls itself recursively.

    Otherwise, it returns an array with true, false, false for any key with the name propName.

    The .reduce then rolls up the array through an or statement.

    function deepCheck(obj,propName) {
      if obj.hasOwnProperty(propName) {             // Performance improvement (thanks to @nem's solution)
        return true;
      }
      return Object.keys(obj)                       // Turns keys of object into array of strings
        .map(prop => {                              // Loop over the array
          if (typeof obj[prop] == 'object') {       // If property is object,
            return deepCheck(obj[prop],propName);   // call recursively
          } else {
            return (prop == propName);              // Return true or false
          }
        })                                          // The result is an array like [false, false, true, false]
        .reduce(function(previousValue, currentValue, index, array) {
          return previousValue || currentValue;
        }                                           // Do an 'or', or comparison of everything in the array.
                                                    // It returns true if at least one value is true.
      )
    }
    
    deepCheck(object,'value'); // === true
    

    PS: nem035's answer showed how it could be more performant: his solution breaks off at the first found 'value.'

提交回复
热议问题