BadVolt BadVolt - 1 month ago 24
Javascript Question

JS object has property deep check

Let's say we have JS object:

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


How can we check if
value
property exists?
I can see only 2 ways:

First one:

if(object && object.innerObject && object.innerObject.deepObject && object.innerObject.deepObject.value) {
console.log('We found it!');
}


Second one:

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


But is there way to do deep check? Let's say, something like:

object['innerObject.deepObject.value']


or

object.hasOwnProperty('innerObject.deepObject.value')

Answer

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');