I get a Javascript Object from my server, which depicts a filesystem. Now I want to get the path of all files in the system, e.g. the endpoints of the tree.
File structure example:
└── pages
└── services
└── project
│── headline
│── test
│ └── text
│ └── picture
│── text
Readable JSON:
{
"path":"/pages/services/project",
"is_dir":true,
"children":[
{
"path":"/pages/services/project/headline",
"is_dir":false,
"children":[
]
},
{
"path":"/pages/services/project/text",
"is_dir":false,
"children":[
]
},
{
"path":"/pages/services/project/test/",
"is_dir":true,
"children":[
{
"path":"/pages/services/project/test/text",
"is_dir":false,
"children":[
]
},
{
"path":"/pages/services/project/test/picture",
"is_dir":false,
"children":[
]
}
]
}
] }
Expected output:
/pages/services/project/headline
/pages/services/project/text
/pages/services/project/test/text
/pages/services/project/test/picture
I played around a little bit with recursion and made a dumb function that works when a dir has only one child. My Problem is that I can`t grasp a way to handle more children. Is there a way to iterate over every child?
Here's my code:
var json = {"path":"/pages/services/project", "is_dir":true, "children":[{"path":"/pages/services/project/headline","is_dir":false,"children":[]},{"path":"/pages/services/project/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/","is_dir":true,"children":[{"path":"/pages/services/project/test/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/picture","is_dir":false,"children":[]}]}]};
json.children.forEach(function (child) {
out(goToDeepestPoint(child).path);
});
function goToDeepestPoint(node) {
if (node.is_dir)
return goToDeepestPoint(node.children[0]);
else
return node;
}
function out()
{
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
<pre id="output"></pre>