Created
September 30, 2020 22:34
-
-
Save mturnwall/12e0cd324f6c42844faa251f883d4a51 to your computer and use it in GitHub Desktop.
Function to get a value from an object regardless of the object's depth
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
/** | |
* | |
* @param {Object} obj - the object you want to get a value out of | |
* @param {Array | String} path - the path to the value, can either be an array `['a', 'b', 'c']` of keys or | |
* string using dotnotation `a.b.c` | |
* @param {*} [defaultValue=undefined] the value you want to return if the key is not found in the object | |
*/ | |
const getObjValue = (obj, path, defaultValue) => { | |
let checkedPath = path; | |
if (!Array.isArray(checkedPath)) { | |
checkedPath = checkedPath.split('.'); | |
} | |
return checkedPath.reduce( | |
(acc, key) => (acc && acc[key] ? acc[key] : defaultValue), | |
obj | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment