gpt4 book ai didi

javascript - 如何在 javascript + HTML 中显示目录结构

转载 作者:行者123 更新时间:2023-12-02 21:13:55 26 4
gpt4 key购买 nike

let 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: "fruits",
path: "/fruits",
children: [{
type: "file",
name: "cat001.jpg",
path: "/animals/cat/images/cat001.jpg"
}]
}
];

我有一个 json 。我想显示一个目录结构。使用递归我能够获取所有项目。我正在尝试添加 ulli 来显示我的目录结构以进行可视化。

我希望它看起来像这样

root
|_ fruits
|___ apple
|______images
|________ apple001.jpg
|________ apple002.jpg
|_ animals
|___ cat
|______images
|________ cat001.jpg
|________ cat002.jpg

使用ulli看起来像这样

我试过这样

function printDir(data) {
if(!data) return null
data.map((i) => {
console.log(i.name)
if (i.children && i.children.length > 0) {
printDir(i.children)
}
})
}

printDir(data)

最佳答案

您可以为 printDir 方法提供一个父列表参数。然后动态创建新的列表和元素并将它们添加到父列表中。也许就像这样...

function printDir(data, listElement) {
if(!data) return null
var list = document.createElement('ul')
data.forEach((i) => {
var item = document.createElement('li')
item.appendChild(document.createTextNode(i.name));
list.appendChild(item)
if (i.children && i.children.length > 0) {
printDir(i.children, list)
}
})
listElement.appendChild(list)
}
printDir(data, document.body)

另请注意,虽然从技术上讲数组映射可以工作,但 forEach 在这里更合适。映射用于创建新数组。

关于javascript - 如何在 javascript + HTML 中显示目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61022657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com