I'm facing an issue with transforming the parent-child relationship in my data structure. Currently, it looks like this:
{
"id": 7,
"name": "Folder 1",
"parent_folder": null,
"folders": [
{
"id": 8,
"name": "Folder 1-1",
"parent_folder": 7
},
{
"id": 10,
"name": "Folder 1-2",
"parent_folder": 7
}
],
},
{
"id": 8,
"name": "Folder 1-1",
"parent_folder": 7,
"folders": [
{
"id": 9,
"name": "Folder 1-1-1",
"parent_folder": 8
}
],
},
{
"id": 9,
"name": "Folder 1-1-1",
"parent_folder": 8,
}
Each folder has its own representation, containing the ID of its parent_folder and its children (only one level down).
The complexity arises when I attempt to navigate deeper into the structure. While I can create a structure like this:
Folder 1
Folder 1-1
Folder 1-2
the problem occurs when I try to add Folder 1-1-1.
To address this challenge, I have devised a solution which is detailed below. The process involves retrieving folder data from an API endpoint and working solely on that response. The snippet begins after fetching the response:
var tempFolderList = [];
var f = response.data.folders;
for (var folder in f) {
if (f[folder].parent_folder) {
console.log("PARENT TEMPLATE FOLDER FOUND");
// Create temporary variable
var tempChildFolder = {
id: f[folder].id,
name: f[folder].name,
parent_folder: f[folder].parent_folder,
children: [],
};
var attv = this.addToTree(tempFolderList, folder, tempChildFolder, f)
console.log("attv: " + attv)
if (attv) {
this.tempFolderList = attv
}
else {
tempFolderList.push(tempChildFolder)
}
// Check if id from current iteration is in temp Folder list
// if yes add to the list, if not :TODO:
// if (
// tempFolderList.find(
// (x) => x.id === f[folder].parent_folder
// )
// ) {
// tempFolderList
// .find((x) => x.id === f[folder].parent_folder)
// .children.push(tempChildFolder);
// }
} else {
// If folder do not have parent folder, just add to temp folder list
var tempFolder = {
id: f[folder].id,
name: f[folder].name,
parent_folder: f[folder].parent_folder,
children: [],
};
tempFolderList.push(tempFolder);
}
console.log(tempFolderList);
}
Below is the addToTree function that empowers the recursive traversal:
addToTree(tempFolderList, folder, tempChildFolder, folderList) {
if (tempFolderList.find((x) => x.id === folderList[folder].parent_folder)) {
// tempFolderList.find((x) => x.id === f[folder].parent_folder).children.push(tempChildFolder)
tempFolderList.push(tempChildFolder)
return tempFolderList;
}
else {
for (var f in tempFolderList) {
var attt = this.addToTree(tempFolderList[f].children, folder, tempChildFolder, folderList)
if (attt) {
tempFolderList[f] = attt
return tempFolderList
}
else {
return false
}
}
}
},