代码之家  ›  专栏  ›  技术社区  ›  Ashwin

继承权的平面目录路径

  •  3
  • Ashwin  · 技术社区  · 7 年前

    我有一个目录路径的平面列表。我想把它转换成层次结构。

    输入格式:

    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": []
      }
    ]
    

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

    谢谢

    1 回复  |  直到 7 年前
        1
  •  3
  •   Endless    7 年前

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