Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
Ashwin Avatar asked Sep 13 '26 09:09

Ashwin


1 Answers

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);
  }
}
like image 84
Endless Avatar answered Sep 14 '26 21:09

Endless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!