Created
January 18, 2015 02:20
-
-
Save whusterj/d7da3b9b04da9dd8fd01 to your computer and use it in GitHub Desktop.
Deep Get in JavaScript
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 deepGet (obj, properties) { | |
// If we have reached an undefined/null property | |
// then stop executing and return undefined. | |
if (obj === undefined || obj === null) { | |
return; | |
} | |
// If the path array has no more elements, we've reached | |
// the intended property and return its value. | |
if (properties.length === 0) { | |
return obj; | |
} | |
// Prepare our found property and path array for recursion | |
var foundSoFar = obj[properties[0]]; | |
var remainingProperties = properties.slice(1); | |
return deepGet(foundSoFar, remainingProperties); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment