I'm in the process of converting these code snippets into smaller ones using recursion. However, I've hit a roadblock while trying to implement a for
loop.
The dictionary I am working with is: var structure = [];
and it has the following structure:
"path": path,
"children": []
I am populating this dictionary by parsing a JSON file. One of the paths from the JSON file looks like this: "path": "Assignment_1/src/com",
. To rebuild this structure within my structure
dictionary, I split the path using `/` and attempt to fill in the necessary parts. The first part, "path": "Assignment_1/",
, goes into the main structure. The subsequent parts, such as "path": "Assignment_1/src/",
, get inserted into the respective children
dictionaries.
Here's how I'm currently achieving this without using recursion:
if(path.split("/").length == 2) {
if(type == "tree") {
var path0 = path.split("/")[0];
var path1 = path.split("/")[1];
for(var j = 0; j < structure.length; j++) {
var foundPath = structure[j]["path"];
if(foundPath == path0) {
structure[j]["children"].push({
"path": path1,
"children": []
})
}
}
}
}
if(path.split("/").length == 3) {
if(type == "tree") {
var path0 = path.split("/")[0];
var path1 = path.split("/")[1];
var path2 = path.split("/")[2];
for(var j = 0; j < structure.length; j++) {
var foundPath = structure[j]["path"];
if(foundPath == path0) {
for(var k = 0; k < structure[j]["children"].length; k++) {
var foundPath = structure[j]["children"][k]["path"];
if(foundPath == path1) {
structure[j]["children"][k]["children"].push({
"path": path2,
"children": []
})
}
}
}
print(structure);
}
}
}
Now, I aim to streamline this process so that it automatically traverses all folders and populates my structure
dictionary. I initially experimented with while
loops, but encountered challenges with these statements:
structure[j]["children"].push({ })
structure[j]["children"][k]["children"].push({ })
These sections proved to be complex to program. Any assistance or guidance on simplifying this would be greatly appreciated!
UPDATE
Input (a part of it):
{
"path": "Folder_1/src/com",
"mode": "040000",
"type": "tree"
},
Output: