Created
August 19, 2021 17:47
-
-
Save mike-pete/cb855674c0b9773688cba1f46c8acc5c to your computer and use it in GitHub Desktop.
Get nested data at path (loop vs recursion)
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
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