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("https://stackoverflow.com/").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)

Leave a Comment