Create a tree from a list of strings containing paths of files - javascript

You can create this structure using forEach method to loop each path and split it to array on /, then you can also use reduce method to create nested objects.

let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];

let result = [];
let level = {result};

paths.forEach(path => {
  path.split('/').reduce((r, name, i, a) => {
    if(!r[name]) {
      r[name] = {result: []};
      r.result.push({name, children: r[name].result})
    }
    
    return r[name];
  }, level)
})

console.log(result)

You could take an iterative approach for every found name part and get an object and return the children for the next search.

var paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
    result = paths.reduce((r, p) => {
        var names = p.split('/');
        names.reduce((q, name) => {
            var temp = q.find(o => o.name === name);
            if (!temp) q.push(temp = { name, children: [] });
            return temp.children;
        }, r);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

So, first off, I am going to assume this is in Node.js, second, I am currently at home so I don't have access to node.js at the moment so I had no real way of testing the code, however the following code should work.

What you need to do is check the contents of the folder and then make a check to see if an item in the folder is a directory or not, if true, call the function again with the new path (a.k.a. recursion).

So first you start by reading the folder, add each item's name to the .name property of the object, then you check if it's a folder or not, if it is, recursive for that path. Keep returning an array of objects back (this will be added to the .children property.

var fs = require('fs');

var filetree = DirToObjectArray('path/to/folder/');

function DirToObjectArray(path) {
        var arr = [];
    var content =  fs.readdirSync(path, { withFileTypes: true });
        for (var i=0; i< content.length; i++) {
        var obj = new Object({
        name: "",
        children: []
     });

     obj.name = content[i].name;

     if (content[i].isDirectory()) {
       obj.children = DirToObjectArray(path + content[i].name + "/");
     }

            arr.push(obj);
   }
   return arr;
}

If you are not using node.js but in-browser javascript, I can't help you with that