Last active
February 11, 2018 03:16
-
-
Save stefanmaric/c641f0eae5a947c5ea2a80c450a04c3c to your computer and use it in GitHub Desktop.
Javascript recursive path / get function in plain ES5 and ES6
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
/** | |
* Gets the value at route of object. | |
* Look at: https://lodash.com/docs/4.17.4#get | |
* | |
* @param {Array|string} route The path of the property to get. | |
* @param {Object} obj The object to query. | |
* @return {*} Resolved value, or undefined. | |
*/ | |
function path (route, obj) { | |
if (!Array.isArray(route)) return path(route.split('.'), obj) | |
if (!route.length) return obj | |
return obj === Object(obj) && obj.hasOwnProperty(route[0]) | |
? path(route.slice(1), obj[route[0]]) | |
: void 0 | |
} |
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
/** | |
* Gets the value at route of object. | |
* Look at: https://lodash.com/docs/4.17.4#get | |
* | |
* @param {Array|string} route The path of the property to get. | |
* @param {Object} obj The object to query. | |
* @return {*} Resolved value, or undefined. | |
*/ | |
const path = (route, obj) => !Array.isArray(route) | |
? path(route.split('.'), obj) | |
: !route.length | |
? obj | |
: obj === Object(obj) && obj.hasOwnProperty(route[0]) | |
? path(route.slice(1), obj[route[0]]) | |
: void 0 | |
export default path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment