层次结构的平面目录路径

Flat directory path to heirarchy

我有一个简单的目录路径列表。我想将其转换为层次结构。

输入格式:

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

输出格式

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

在我的输入中,我不能有任何父参数。我的进度 fiddle 在这里 - https://jsfiddle.net/ashwyn/Laamg14z/2/

谢谢。

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);
  }
}