我有一个包含嵌套数组的数据结构-我想显示数据使其看起来像文件结构-因此嵌套数据表示为嵌套文件/文件夹。但是,在控制台日志记录中,递归函数返回的内容并不表示数据结构的嵌套性质。
这是我的数据结构:
const data = {
"root": [
{
"type": "folder",
"name": "one",
"children": [
{
"type": "folder",
"name": "one",
"children": []
},
{
"type": "file",
"name": "two",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
},
{
"type": "file",
"name": "four",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
}
]
},
{
"type": "file",
"name": "two",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
},
{
"type": "file",
"name": "three",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
},
{
"type": "file",
"name": "four",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
}
]
}
还有我的递归函数:
const recurse = (data, children = false) => {
data.forEach(object => {
if (object.type === 'folder') {
recurse(object.children, true)
}
if (children) {
console.log(' ' + object.type + ' ' + object.name);
} else {
console.log(object.type + ' ' + object.name);
}
})
}
recurse(data.root)
和控制台日志:
' folder one'
' file two'
' file four'
'folder one'
'file two'
'file three'
'file four'
因此,该功能是从内部开始打印结构。如果要以反映数据结构嵌套性质的方式显示它,应该使用哪种方法?预先感谢
答案 0 :(得分:2)
@ j.xavier.atero比我快一点。 :)
我认为您必须将递归放在函数的末尾。这样,您将首先获得folder one
,然后再获得其子级。
const recurse = (data, children = false) => {
data.forEach(object => {
if (children) {
console.log(' ' + object.type + ' ' + object.name);
} else {
console.log(object.type + ' ' + object.name);
}
if (object.type === 'folder') {
recurse(object.children, true)
}
})
}
recurse(data.root)
评论更新
我想为递归函数添加一个额外的参数。
const recurse = (data, level = 0) => {
data.forEach(object => {
console.log(Array(level).join(' ') + object.type + ' ' + object.name);
if (object.type === 'folder') {
recurse(object.children, level + 1)
}
})
}
recurse(data.root)
这将跟踪递归函数的深度。如果它是孩子了,您甚至不需要检查。
答案 1 :(得分:1)
您应该在进行递归之前打印元素的名称:
const recurse = (data, children = false) => {
data.forEach(object => {
if (children) {
console.log(' ' + object.type + ' ' + object.name);
} else {
console.log(object.type + ' ' + object.name);
}
if (object.type === 'folder') {
recurse(object.children, true)
}
})
}
recurse(data.root)