Search code examples
javascriptnode.jstreehierarchydirectory-structure

Flat directory path to heirarchy


I have a flat list of directory paths. I want to convert that to a hierarchy.

Input format:

var paths = [
  "A/B",
  "A/B/C",
  "A/B/C/D",
  "A/B/C/E",
    "F" 
];

Output format

[
  {
    "name": "A",
    "children": [
      {
        "name": "B",
        "children": [
          {
            "name": "C",
            "children": [
              {
                "name": "D",
                "children": []
              },
              {
                "name": "E",
                "children": []
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "name": "F",
    "children": []
  }
]

In my input ,I cannot have any parent parameter. My in progress fiddle is here - https://jsfiddle.net/ashwyn/Laamg14z/2/

Thanks.


Solution

  • var paths = [
      "A/B",
      "A/B/C",
      "A/B/C/D",
      "A/B/C/E",
    	"F" 
    ];
    
    /* Output
    [{"name":"A","children":[{"name":"B","children":[{"name":"C","children":[{"name":"D","children":[]},{"name":"E","children":[]}]}]}]},{"name":"F","children":[]}]
    */
    
    console.log(convertToHierarchy(paths).children)
    
    function convertToHierarchy(paths /* array of array of strings */) {
      // Build the node structure
      const rootNode = {name:"root", children:[]}
      
      for (let path of paths) {
        buildNodeRecursive(rootNode, path.split('/'), 0);
      }
      
      return rootNode;
    }
    
    function buildNodeRecursive(node, path, idx) {
      if (idx < path.length) {
        let item = path[idx]
        let dir = node.children.find(child => child.name == item)
        if (!dir) {
          node.children.push(dir = {name: item, children:[]})
        }
        buildNodeRecursive(dir, path, idx + 1);
      }
    }