Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Last active February 11, 2018 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanmaric/c641f0eae5a947c5ea2a80c450a04c3c to your computer and use it in GitHub Desktop.
Save stefanmaric/c641f0eae5a947c5ea2a80c450a04c3c to your computer and use it in GitHub Desktop.
Javascript recursive path / get function in plain ES5 and ES6
/**
* 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
}
/**
* 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