Javascript 平面数组到深嵌套对象数组
我正在尝试获取路径的平面数组,并创建对象的嵌套数组。我遇到的问题是生成子节点的递归部分 起始阵列:Javascript 平面数组到深嵌套对象数组,javascript,arrays,recursion,ecmascript-6,Javascript,Arrays,Recursion,Ecmascript 6,我正在尝试获取路径的平面数组,并创建对象的嵌套数组。我遇到的问题是生成子节点的递归部分 起始阵列: const paths = [ '/', '/blog', '/blog/filename', '/blog/slug', '/blog/title', '/website', '/website/deploy', '/website/infrastructure', '/website/infrastructure/aws-notes', ]; 具有所需的
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,
];
}, []);
到目前为止,我已经尝试了一些方法,但最终以无限循环或糟糕的结构告终:
[
{
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
路径=['/'、'/blog'、'/blog/filename'、'/blog/slug'、'/blog/title'、'/website'、'/website/deploy'、'/website/infrastructure'、'/website/infrastructure/aws notes'],
结果=路径。减少((r,路径)=>{
path.split(/(?=\/)/).reduce((a,i,p)=>{
var temp=a.find(o=>o.path==p.slice(0,i+1).join(“”));
如果(!temp){
a、 推送(temp={path,子项:[]});
}
返回临时儿童;
},r);
返回r;
}, []);
控制台日志(结果)代码>
。作为控制台包装{最大高度:100%!重要;顶部:0;}
@gordie,对不起。请问一个新问题。