Skip to Content

has()

Check nested objects for values.

JavaScript July 15, 2020

Usage

JavaScript
nebula.has(obj, prop)

Parameters

obj
(Required) (Object) The object name to look into
Default: None

prop
(Required) (String) The property too look for
Default: None

Parameter Notes

Important: pass prop as a string with object notation (period separated).

Request or provide clarification »

Examples

The main benefit of using this function is that it handles nested objects with a single call

JavaScript
if ( nebula.has(nebula, 'user.client.remote_addr') ){
    console.log(nebula.user.client.remote_addr);
}

This function can not detect if an object is defined, so that must be done alongside

JavaScript
if ( typeof google != "undefined" && nebula.has(google, 'maps') ){
    //Do something if google.maps is defined
} else {
    //Do something else if google is undefined or doesn't have maps.
}

This works for navigator support detection too.

JavaScript
if ( nebula.has(navigator, 'getBattery') ){
    //Do something with the Battery API
}

Or use it with Modernizr (as an alternative to yep/nope). Make sure Modernizr is enabled, though, or this would error out.

JavaScript
if ( typeof Modernizr != 'undefined' && nebula.has(Modernizr, 'batteryapi') ){
    //Do something with the Battery API
}

Additional Notes

Returns boolean.

Works well with nested objects- this helps prevent long conditionals like if ( nebula && nebula.client && nebula.client.remote_addr ){...}

Note: This function can not detect if an object is defined, so that must be done prior or alongside this function. See above example.

Source File

Located in /assets/js/nebula.js on line 4266.

JavaScript
nebula.has = function(obj, prop){
    var parts = prop.split('.');
    for ( var i = 0, l = parts.length; i < l; i++ ){
        var part = parts[i];
        if ( obj !== null && typeof obj === "object" && part in obj ){
            obj = obj[part];
        } else {
            return false;
        }
    }

    return true;
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.has = function(obj, prop){
    //Write your own code here, leave it blank, or return false.
}