Object has-property-deep check in JavaScript

后端 未结 8 1934
走了就别回头了
走了就别回头了 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');
    
    0 讨论(0)
  • 2020-12-01 21:59

    Try this nice and easy solution:

    public hasOwnDeepProperty(obj, path)
    {
        for (var i = 0, path = path.split('.'), len = path.length; i < len; i++)
        {
            obj = obj[path[i]];
            if (!obj) return false;
        };
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题