const data = {
name: 'all',
children: [
{
name: '图片',
children: [
{
name: 'image1.jpg'
},
{
name: '风景',
children: [
{
name: 'guilin.jpg'
},
{
name: 'hainan.jpg'
}
]
},
{
name: 'image2.jpg'
}
],
},
{
name: '视频',
children: [
{
name: 'video1.mp4'
},
{
name: 'video2.mp4'
}
]
},
{
name: '文档',
children: [
{
name: 'document1.doc'
},
{
name: '小说',
children: [
{
name: 'novel.txt'
},
{
name: 'novel2.txt'
}
]
},
{
name: 'document2.doc'
}
]
}
]
}
const dfs = (tree, ope, filter) => {
const walkAndCopy = (tree, depth = 1) => {
if(filter(tree.name)) {
const copy = {}
ope(tree.name, depth)
copy.name = tree.name
if(tree.children) {
copy.children = []
tree.children.forEach((node) => {
const subTree = walkAndCopy(node, depth + 1)
subTree && copy.children.push(subTree)
})
}
return copy
}
}
return walkAndCopy(tree)
}
const copy = dfs(data,(name, depth) => {}, (name) => {
return name.indexOf('1') === -1
})
document.write(JSON.stringify(copy))
console