Skip to content

Instantly share code, notes, and snippets.

@mike-pete
Created August 19, 2021 17:47
Show Gist options
  • Save mike-pete/cb855674c0b9773688cba1f46c8acc5c to your computer and use it in GitHub Desktop.
Save mike-pete/cb855674c0b9773688cba1f46c8acc5c to your computer and use it in GitHub Desktop.
Get nested data at path (loop vs recursion)
const data = {
a:{
b:{
c:{"neat":"right!?"}
}
}
}
function getDataAtPath(path, currentData){
for (let i in path){
currentData = currentData[path[i]]
if (i == path.length-1){
console.log(currentData)
}
}
}
function getDataAtPathRecursive(path, currentData, i=0){
currentData = currentData[path[i]]
if (i == path.length-1){
console.log(currentData)
}
else {
getDataAtPathRecursive(path, currentData, ++i)
}
}
const path = ['a','b','c']
getDataAtPath(path, data)
getDataAtPathRecursive(path, data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment