Last active
February 15, 2016 12:49
-
-
Save Reshetnyak/da24411150b7e94c7f07 to your computer and use it in GitHub Desktop.
Get object property if it exist. Nesting depth doesn't matter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get object property if it exist. | |
* @param {string} propStr - property of object with any level of nesting. 'person.address.home.floor' | |
* @returns {*} needed property | |
*/ | |
function getPropIfExist(propStr){ | |
var props = propStr.split('.'); | |
var lastIndex = props.length - 1; | |
var i = 0; | |
return getProp(window, props[0]); | |
/** | |
* Try to get object property recursively | |
* @param {*} obj - object to check for property existing | |
* @param {string} prop - needed property name | |
* @returns {*} needed property or undefined | |
*/ | |
function getProp(obj, prop){ | |
if ( typeof obj === 'object' || typeof obj === 'function' ){ | |
if (i < lastIndex){ | |
i += 1; | |
return getProp( obj[prop], props[i] ); | |
} else { | |
return obj[prop] | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment