Currently, I have been assigned the task of organizing the files directory efficiently. All documents and files are stored in a flat array for simplicity. Each file has a uniqueId property that indicates its parent directory. The flat array is sorted based on the uniqueId, ensuring that each child follows its parent.
Here is an illustration of the flat array:
[{
id: 1,
uniqueId: '1',
name: 'folder1',
dir: true
},
{
id: 2,
uniqueId: '1.2',
name: 'test1',
dir: false
},
{
id: 3,
uniqueId: '1.2.3',
name: 'test2'
dir: false
},
{
id: 4,
uniqueId: '1.2.4',
name: 'test3'
dir: true
},
{
id: 3,
uniqueId: '1.3',
name: 'test23'
dir: true
},
{
id: 1,
uniqueId: '1.3.1',
name: 'test6',
dir: true
},
]
This effectively represents the file directory tree:
1
1.2
1.2.3
1.2.4
1.3
1.3.1
The objective is to display directories first, specifically those with dir: true
. Consequently, the tree above would be reordered as follows:
1
1.3
1.3.1
1.2
1.2.4
1.2.3
To achieve this, I have decided to convert the flat array into nested objects, arrange the children of each object accordingly, and then revert back to a flat array structure. This means transforming the flat array into the following format:
{
id: 1,
uniqueId: '1',
name: 'folder1',
dir: true
childs: [
{
id: 2,
uniqueId: '1.2',
name: 'test1',
dir: false,
childs: [
{
id: 3,
uniqueId: '1.2.3',
name: 'test2'
dir: false
},
{
id: 4,
uniqueId: '1.2.4',
name: 'test3'
dir: true
}
]},
{
id: 3,
uniqueId: '1.3',
name: 'test23'
dir: true,
childs: [
{
id: 1,
uniqueId: '1.3.1',
name: 'test23'
dir: true
}
]
}
}]
I am struggling to find a way to convert the flat array into the desired nested object configuration. While I do have a function that returns a current object's children isChild(parent, objectToCheck), incorporating recursion seems necessary but challenging.
If you can provide assistance in converting it into the desired nested object, I would greatly appreciate it.
Furthermore, any alternative suggestions for sorting the flat array are welcomed! Perhaps there exists a more efficient technique without the need to constantly switch between structures?
Thank you sincerely in advance!