I'm trying to search a nested json array for a single object with a matching name. My data structure looks like this:
[
{
"type": "directory",
"name": "/home/user/test-tree",
"contents": [
{
"type": "directory",
"name": "my-folder",
"contents": [
{
"type": "directory",
"name": "nested-folder",
"contents": []
}
]
},
{
"type": "directory",
"name": "node_modules",
"contents": [
{
"type": "directory",
"name": "gunzip-file",
"contents": []
}
]
}
]
}
]
So in this example, I could be searching for a directory called "node_modules" and it should return that entire object, including its contents. This is just a sample, my actual dataset could be pretty big - the tree could represent all directories on a filesystem for example.
This is the code that I'm using right now - it seems to work for this example but it doesn't seem to work properly with larger datasets, and I can't really see what's wrong with it so if someone can spot anything I'd appreciate it.
function treeSearch(array, dirName) {
for (let i = 0; i < array.length; i++) {
if (array[i].name === dirName) {
return array[i]
}
else if (array[i].contents) {
if (array[i].contents.length > 0) {
return treeSearch(array[i].contents, dirName)
}
}
}
}