我有這個樹結構:
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));
它不會使某些元素變平。任何想法如何解決?
uj5u.com熱心網友回復:
這是使用flatMap()和遞回的解決方案:
const flatten = (array) => array.flatMap(({ type, name, path, children }) => [
{ type, name, path },
...flatten(children || [])
]);
完整片段:
const 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"
}
]
}]
}]
}];
const flatten = (array) => array.flatMap(({type, name, path, children}) => [
{ type, name, path },
...flatten(children || [])
]);
console.log(flatten(data));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456416.html
標籤:javascript 数组 树 tree-structure
上一篇:通過初始化獲取句柄位置
下一篇:填充多維陣列動態
