Object has-property-deep check in JavaScript

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

    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'
           }
       }
    }
    
    obj.hasOwnNestedProperty('innerObject.deepObject.value');
    

提交回复
热议问题