将树结构展平为数组
我有这个树结构:
data =
{
[
{
type: "folder"
name: "animals"
path: "/animals"
children :
[
{
type: "folder"
name: "cat"
path: "/animals/cat"
children:
[
{
type: "folder"
name: "images"
path: "/animals/cat/images"
children:
[
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat001.jpg"
},
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat002.jpg"
}
]
}
]
}
]
}
]
}
我想把它变成
[
{
type: "folder"
name: "animals"
path: "/animals"
},
{
type: "folder"
name: "cat"
path: "/animals/cat"
},
{
type: "folder"
name: "images"
path: "/animals/cat/images"
},
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat001.jpg"
},
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat002.jpg"
}
]
我想出的这个功能,但似乎不起作用
function flatten(nodes, flattedNodes) {
for (let index = 0; index < nodes.length; index++) {
flattedNodes.push(nodes[index]);
if (nodes[index].children !== undefined)
if (nodes[index].children.length > 0)
flatten(nodes[index].children, flattedNodes);
}
}
let flattedTree = [];
flatten(data, flattedTree);
console.log(JSON.stringify(flattedTree, null, 4));
它不会展平某些元素。有什么想法如何修复吗?
I have this tree structure:
data =
{
[
{
type: "folder"
name: "animals"
path: "/animals"
children :
[
{
type: "folder"
name: "cat"
path: "/animals/cat"
children:
[
{
type: "folder"
name: "images"
path: "/animals/cat/images"
children:
[
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat001.jpg"
},
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat002.jpg"
}
]
}
]
}
]
}
]
}
I want to turn it into
[
{
type: "folder"
name: "animals"
path: "/animals"
},
{
type: "folder"
name: "cat"
path: "/animals/cat"
},
{
type: "folder"
name: "images"
path: "/animals/cat/images"
},
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat001.jpg"
},
{
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat002.jpg"
}
]
I came up with this function, but seems does not work
function flatten(nodes, flattedNodes) {
for (let index = 0; index < nodes.length; index++) {
flattedNodes.push(nodes[index]);
if (nodes[index].children !== undefined)
if (nodes[index].children.length > 0)
flatten(nodes[index].children, flattedNodes);
}
}
let flattedTree = [];
flatten(data, flattedTree);
console.log(JSON.stringify(flattedTree, null, 4));
It does not flatten some elements. Any ideas how to fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是使用
flatMap() 的解决方案
和递归:完整片段:
Here's a solution using
flatMap()
and recursion:Complete snippet: