Skip to content

Instantly share code, notes, and snippets.

@ronaldroe
Last active February 28, 2023 14:32
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 ronaldroe/3b1bd9551593aaf47d826f115c3a4b9e to your computer and use it in GitHub Desktop.
Save ronaldroe/3b1bd9551593aaf47d826f115c3a4b9e to your computer and use it in GitHub Desktop.
Recurse JavaScript Object from Path
/**
* Recursive function to walk down into the config object and return the requested data
*
* @param {string[]} pathArray Array containing the paths to the requested key
* @param {Object} inputObj The object being traversed.
* @param {number} [idx=0] Current index. Used internally to determine where in the pathArray we are
*
* @returns {any|null} Requested config setting(s)
*/
const recurseConfigPath = (pathArray, inputObj, idx = 0) => {
// For each level of the array, get the next path
let output;
const currPath = pathArray[idx];
// Push this object into the output
output = inputObj[currPath];
if (typeof pathArray[++idx] !== 'undefined') {
// The path goes deeper, recurse into the next index
output = recurseConfigPath(pathArray, inputObj[currPath], idx);
}
return output ?? null;
}
// Usage:
const configObj = {
root: {
child: {
data: 'string'
}
}
};
const path = ['root', 'child', 'data'];
const data = recurseConfigPath(path, configObj);
console.log(data); // 'string'
// Can also do arrays, if index is known:
const configObj = {
root: {
child: [
'string'
]
}
};
const path = ['root', 'child', 0];
const data = recurseConfigPath(path, configObj);
console.log(data); // 'string'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment