Last active
August 29, 2015 14:19
-
-
Save jeremenichelli/63b75db9434272b16d1d to your computer and use it in GitHub Desktop.
Given a path, get property of an object
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
function getFromPath(obj, path, defaultValue) { | |
var props = path.split('.'), | |
newObj = obj; | |
for (var i = 0, len = props.length; i < len; i++) { | |
if (newObj[props[i]] !== null && newObj[props[i]] !== undefined) { | |
newObj = newObj[props[i]]; | |
} else { | |
return defaultValue || null; | |
} | |
} | |
return newObj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment