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

标签 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 来检索父节点,但我不知道如何将节点作为子节点推送到正确的嵌套节点中。注意:我已经为示例提取了一些代码,请原谅任何语法/拼写问题。

最佳答案

您可以采用嵌套方法,通过获取路径并将它们拆分并检查具有该路径的对象是否已经存在。如果不推送一个新对象。

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

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

关于javascript - 平面数组到深层嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548310/

相关文章:

javascript - 如何从另一个页面关闭模态表单

javascript - React.js 在导航离开页面或页面刷新时触发事件

javascript - 属于数组中同一字段的值的累积和

Javascript无限类别深度树

c - 为什么我在 C 中的递归函数会导致堆栈溢出?

javascript - Fabric js如何模拟鼠标按下事件

javascript - 如何从 eBay 通知中获取数据

无法进入 "if"条件。为什么?

arrays - 逐个元素构建 Julia 数组的有效方法

python - 旅行推销员: Get all possible Paths with recursion