【问题标题】:How to unflatten a nodes array object to a nested object which represents a directory structure如何将节点数组对象展开为表示目录结构的嵌套对象
【发布时间】:2020-06-16 06:51:56
【问题描述】:

您如何编写一个函数,该函数将对表示目录结构或路由路径树的对象的节点数组执行非扁平化转换。此外,如果任何路径都涉及创建空节点,您如何为结果结构创建这些节点。空目录只有它们的路径和子键。这是一个示例节点数组:

比如nodes = [{id: 50, path: "/apple/banana"}],返回

{
  "path": "/",
  "children": [
    {
      "path": "/apple",
      "children": [
        {
          "id": 50,
          "path": "/apple/banana",
          "children": []
        }
      ]
    }
  ]
}

我有这个:

const tree = { path: '/', children:[] }
const sortedNodes = nodes.sort((a, b) => (a.path.split('/').length - b.path.split('/').length));
sortedNodes.forEach(node => {
  const dirs = node.path.split('/').slice(1)
  let traversed = tree // Hold the reference of tree

  dirs.forEach((dir) => {
    const foundChild = traversed.children.find(child => child.path.split('/').slice().pop() === dir)
    foundChild ? traversed = foundChild : traversed.children.push({ path: node.path, id: node.id, children: [] });   
  })
})
console.log(tree);

【问题讨论】:

    标签: javascript tree hierarchy flatten


    【解决方案1】:

    您可以拆分路径并获取用于迭代嵌套对象的部分。

    var nodes = [{ id: 50, path: "/apple/banana" }],
        tree = nodes
            .reduce((t, { id, path }) => {
                path.split(/\//).reduce((r, _, i, p) => {
                    var path = p.slice(0, i + 1).join('/') || '/';
                        temp = r.children.find(q => q.path === path);
                    if (!temp) r.children.push(temp = { path, children: [] });
                    return temp;
                }, t).id = id;
                return t;
            }, { children: [] })
           .children;
    
    console.log(tree);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2020-12-18
      • 2018-03-10
      • 2018-10-22
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多