I'm trying to take a flat array of paths, and create nested array of objects. The trouble i'm having is with the recursive part of generating children nodes...
Starting array:
const paths = [
'/',
'/blog',
'/blog/filename',
'/blog/slug',
'/blog/title',
'/website',
'/website/deploy',
'/website/infrastructure',
'/website/infrastructure/aws-notes',
];
With a desired output structure:
[
{
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',
}
],
},
],
},
]
Here's where i'm at so far, i've tried a few things but ultimately ends in infinite loops or poor structure:
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,
];
}, []);
I've tried array.find|some|filter to retrieve the parent, but i'm at a loss how to push the node as a child into the correct nested node. NOTE: i've extracted some code for the example, pardon any syntax/spelling issues.