Я пытаюсь взять плоский массив путей и создать вложенный массив объектов.У меня проблема с рекурсивной частью генерации дочерних узлов ...
Начальный массив:
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
, чтобы получить родителя, но яЯ в растерянности, как подтолкнуть узел как ребенка в правильный вложенный узел.ПРИМЕЧАНИЕ: я извлек код для примера, извините за любые проблемы синтаксиса / орфографии.