Last active
January 23, 2020 13:23
-
-
Save edvaldoszy/aa43a4a6a9c470b71f61a0b27dd96c1b to your computer and use it in GitHub Desktop.
Get path from JavaScript Object
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
/** | |
* Get object path value or return defaultValue | |
* @param {object} object Object to get path value | |
* @param {string[]} keys Object path in an array | |
* @param {any} defaultValue Default value if the path does not exists | |
*/ | |
function getPath(object, keys, defaultValue) { | |
if (keys.length === 1) { | |
const [curr] = keys; | |
return object[curr]; | |
} | |
if (keys.length > 1) { | |
const [curr, ...rest] = keys; | |
const nextObject = object[curr]; | |
if (!nextObject || typeof nextObject !== 'object') { | |
return defaultValue; | |
} | |
return getPath(nextObject, rest); | |
} | |
return defaultValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment