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"
}]
}
];
I have a json.I want to show a directory structure.using recursion I am able to get all items. I am trying to add ul
and li
to show my directory structure for visualization.
i want it looks like this
root
|_ fruits
|___ apple
|______images
|________ apple001.jpg
|________ apple002.jpg
|_ animals
|___ cat
|______images
|________ cat001.jpg
|________ cat002.jpg
it looks like this using ul
and li
I tried like that
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)
You could give the printDir
method a parent list parameter. And then you create new lists and elements dynamically and add them to the parent list. Maybe like so...
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)
Also note that while technically an array map would work, a forEach is more suitable here. Maps are for creating new arrays.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.