Last active
October 28, 2015 19:10
-
-
Save wejrowski/a407fe384e3af9c3356d to your computer and use it in GitHub Desktop.
Get path value
This file contains hidden or 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
// via http://www.redotheweb.com/2015/09/18/declarative-imperative-js.html | |
function getValue(object, propertyName) { | |
if (!propertyName) throw new Error('Impossible to set null property'); | |
return typeof object === 'undefined' ? undefined : object[propertyName]; | |
} | |
function getNestedValue(object, propertyName) { | |
return propertyName.split('.').reduce(getValue, object); | |
} | |
var myObj = { | |
x: "hi", | |
john: { | |
first: "j", | |
last: "doe", | |
address: { | |
street: "103 10th st", | |
state: "AZ" | |
} | |
}, | |
bill: { | |
first: "bill", | |
last: "johnson" | |
} | |
}; | |
getNestedValue(myObj, "john.address.street"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment