如何将节点数组对象取消填充为表示目录结构的嵌套对象



如何编写一个函数,该函数将对表示目录结构或路由路径树的对象的节点数组执行不加修饰的转换。此外,如果任何路径都涉及创建空节点,如何为结果结构创建这些节点。空目录只有它们的路径和子键。下面是一个节点阵列示例:

例如,如果nodes = [{id: 50, path: "/apple/banana"}],则返回

{
"path": "/",
"children": [
{
"path": "/apple",
"children": [
{
"id": 50,
"path": "/apple/banana",
"children": []
}
]
}
]
}

我有这个:

const tree = { path: '/', children:[] }
const sortedNodes = nodes.sort((a, b) => (a.path.split('/').length - b.path.split('/').length));
sortedNodes.forEach(node => {
const dirs = node.path.split('/').slice(1)
let traversed = tree // Hold the reference of tree
dirs.forEach((dir) => {
const foundChild = traversed.children.find(child => child.path.split('/').slice().pop() === dir)
foundChild ? traversed = foundChild : traversed.children.push({ path: node.path, id: node.id, children: [] });   
})
})
console.log(tree);

您可以分割路径并获取用于迭代嵌套对象的部分。

var nodes = [{ id: 50, path: "/apple/banana" }],
tree = nodes
.reduce((t, { id, path }) => {
path.split(///).reduce((r, _, i, p) => {
var path = p.slice(0, i + 1).join('/') || '/';
temp = r.children.find(q => q.path === path);
if (!temp) r.children.push(temp = { path, children: [] });
return temp;
}, t).id = id;
return t;
}, { children: [] })
.children;
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新