【发布时间】:2018-11-29 22:05:21
【问题描述】:
我正在尝试采用平坦的路径数组,并创建嵌套的对象数组。我遇到的麻烦是生成子节点的递归部分......
起始数组:
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 来检索父节点,但我不知道如何将节点作为子节点推送到正确的嵌套节点中。注意:我已经为示例提取了一些代码,请原谅任何语法/拼写问题。
【问题讨论】:
标签: javascript arrays recursion ecmascript-6