Skip to content

Instantly share code, notes, and snippets.

@mturnwall
Created September 30, 2020 22:34
Show Gist options
  • Save mturnwall/12e0cd324f6c42844faa251f883d4a51 to your computer and use it in GitHub Desktop.
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
/**
*
* @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