Last active
November 22, 2017 15:04
-
-
Save briancribb/2d85ca89637a7035b51be35ac7b1b359 to your computer and use it in GitHub Desktop.
Return a deep 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
var myObject = { | |
one: { | |
two: { | |
three: 'This is the string you want to see' | |
} | |
} | |
} | |
function getObjectProps(objTarget, strProp) { | |
// objTarget: An object that is several levels deep. | |
// strProp: Property string for that object. | |
// Example call: getObjectProps(myObject, "one.two.three"); | |
// Returns: 'This is the string you want to see' | |
// Reference to the current object, which will be redefined as we drill down into it. | |
// Also making an array by splitting the string along the period. | |
var objTemp = objTarget, | |
arrProp = strProp.split('.'); | |
// Loop through the new array, and go deeper into the object each time. | |
for (var i = 0; i < arrProp.length; i++) { | |
objTemp = objTemp[arrProp[i]]; | |
} | |
// Return the final object property. | |
return objTemp; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment