I need a javascript function to turn an array with file path string to object as follows:
let files = [
"Folder/file.ext",
"Folder/file2.ext",
"Folder/file3.ext",
"Folder/nestedfolder/file.ext",
"Folder2/file1.ext",
"Folder2/file2.ext",
"file1.ext",
"file2.ext",
"file3.ext",
];
listToTree(files);
And It should output an array with an object as follows:
[
{
text: "Folder",
children: [
{text: "file.ext"},
{text: "file1.ext"},
{text: "file2.ext"},
{text: "nestedfolder", children: [{text: "file.ext"}]},
]
},
{
text: "Folder2",
children: [
{text: "file1.ext"},
{text: "file2.ext"},
]
},
{text: "file1.ext"},
{text: "file2.ext"},
{text: "file3.ext"}
];
Here is the current function I am using. but it is not quite there.
function listToTree(files) {
let filestmp = files.map(file => {
if (typeof file === "string") return file;
return file.path
});
let filesl = filestmp.map(fileee => fileToObject(fileee));
return filesl;
}
function fileToObject(filee) {
if (filee.includes("/")) {
// this is a folder
let count = filee.indexOf("/");
return {text: filee.substring(0, count), children: [fileToObject(filee.substring(count + 1))]}
} else {
// this is a file
return {text: filee}
}
}
export default listToTree
it outputs:
[ { text: 'Folder', children: [ { text: 'file.ext' } ] },
{ text: 'Folder', children: [ { text: 'file2.ext' } ] },
{ text: 'Folder', children: [ { text: 'file3.ext' } ] },
{ text: 'Folder',
children:
[ { text: 'nestedfolder', children: [ { text: 'file.ext' } ] } ] },
{ text: 'Folder2', children: [ { text: 'file1.ext' } ] },
{ text: 'Folder2', children: [ { text: 'file2.ext' } ] },
{ text: 'file1.ext' },
{ text: 'file2.ext' },
{ text: 'file3.ext' } ]
now as you can see. each file list array getting its own object. I need to combine the files located in the same folder location.