Skip to content

Instantly share code, notes, and snippets.

@briancribb
Last active November 22, 2017 15:04
Show Gist options
  • Save briancribb/2d85ca89637a7035b51be35ac7b1b359 to your computer and use it in GitHub Desktop.
Save briancribb/2d85ca89637a7035b51be35ac7b1b359 to your computer and use it in GitHub Desktop.
Return a deep property of an object
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