平面数组到深层嵌套对象数组

时间:2018-11-29 22:05:22

标签: javascript arrays recursion ecmascript-6

我正在尝试采用平坦的路径数组,并创建嵌套的对象数组。我遇到的麻烦是生成子节点的递归部分...

起始数组:

const paths = [ 
  '/',
  '/blog',
  '/blog/filename',
  '/blog/slug',
  '/blog/title',
  '/website',
  '/website/deploy',
  '/website/infrastructure',
  '/website/infrastructure/aws-notes',
];

具有所需的输出结构:

[
  { 
    path: '/',
  },
  {
    path: '/blog',
    children: [
      {
        path: '/blog/filename',
      },
      {
        path: '/blog/slug',
      },
      {
        path: '/blog/title',
      }
    ]
  },
  { 
    path: '/website',
    children: [
      {
        path: '/website/deploy',
      },
      {
        path: '/website/infrastructure',
        children: [
          {
            path: '/website/infrastructure/aws-notes',
          }
        ],
      },
    ],
  },
]

到目前为止,我在这里已经尝试过一些方法,但最终以无限循环或不良结构结束:

const getPathParts = (path) => path.substring(1).split('/');
const getPathLevel = (path) => getPathParts(path).length - 1;
const getTree = (paths) => paths.reduce((tree, path, i, paths) => {
  const pathParts = getPathParts(path);
  const pathDepth = getPathLevel(path);
  const current = pathParts[pathDepth];
  const parent = pathParts[pathDepth - 1] || null;
  const item = {
    path,
    children: [],
  };

  if (pathDepth > 0 || parent !== null) {
    // recursive check for parent, push this as a child to that parent?
    return [...tree];
  }

  return  [
    ...tree, 
    item,
  ];
}, []);

我已经尝试过array.find|some|filter来检索父节点,但是我不知如何将节点作为子节点推入正确的嵌套节点中。注意:我已经为示例提取了一些代码,请原谅任何语法/拼写问题。

1 个答案:

答案 0 :(得分:1)

您可以采用嵌套方法,将路径分离并检查路径是否存在。如果没有,推一个新的物体。

稍后返回实际对象的子代。继续进行,直到没有更多路径项目可用为止。

const
    paths = ['/', '/blog', '/blog/filename', '/blog/slug', '/blog/title', '/website', '/website/deploy', '/website/infrastructure', '/website/infrastructure/aws-notes'],
    result = paths.reduce((r, path) => {
        path.split(/(?=\/)/).reduce((a, _, i, p) => {
            var temp = a.find(o => o.path === p.slice(0, i + 1).join(''));
            if (!temp) {
                a.push(temp = { path, children: [] });
            }
            return temp.children;
        }, r);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

对于仅使用最终目录的路径进行创建的情况,可以采用部分创建路径。

这种方法可以防止空子数组。

const
    paths = [
        '/',
        '/blog/filename',
        '/blog/slug',
        '/blog/title',
        '/website/deploy',
        '/website/infrastructure/aws-notes'
    ],
    result = [];

paths.reduce((r, string) => {
    string.split(/(?=\/)/).reduce((o, _, i, p) => {
        o.children = o.children || [];
        var path = p.slice(0, i + 1).join(''),
            temp = o.children.find(o => o.path === path);
        if (!temp) {
            o.children.push(temp = { path });
        }
        return temp;
    }, r);
    return r;
}, { children: result });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }