Last active
February 28, 2023 14:32
-
-
Save ronaldroe/3b1bd9551593aaf47d826f115c3a4b9e to your computer and use it in GitHub Desktop.
Recurse JavaScript Object from Path
This file contains hidden or 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
/** | |
* 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