const treeData = {
name: '1',
children: [{
name: '2',
children: [{
name: '4',
children: []
}, {
name: '5',
children: []
}]
}, {
name: '3',
children: [{
name: '6',
children: []
}, {
name: '7',
children: []
}]
}]
}
function getName(data) {
let ch = data.children
let length = ch.length
let result = []
result.push(data.name)
if (length) {
ch.forEach(item => {
result.push(...getName(item))
})
}
return result
}
function getName2(data) {
let res = []
let tem = []
let queue = [data]
while (queue.length) {
tem = queue
queue = []
res.push(tem.map(item => {
if (item.children.length) queue.push(...item.children)
return item.name
}))
}
return res
}
console.log(getName2(treeData))
console