let qs = [{
value: 'A',
children: [
{
value: 'B',
children: [
{
value: 'D',
children: [
{
value: 'H',
children: []
}
]
},
{
value: 'E',
children: []
}
]
},
{
value: 'C',
children: [
{
value: 'F',
children: []
},
{
value: 'G',
children: []
}
]
}
]
}]
1、普通递归
let list = []
function flatten1(data){
let stack = JSON.parse(JSON.stringify(data))
stack.map((ele) => {
list.push(ele)
if (ele.children) {
flatten1(ele.children)
}
})
return list
}
2、reduce
function flatten2(data) {
return data.reduce((prev, cur) => {
prev.push(cur)
if (cur.children) {
prev.push(...flatten2(cur.children))
}
return prev
}, [])
}
3、模拟栈
function flatten3(data) {
let list = []
let stack = JSON.parse(JSON.stringify(data))
while (stack.length) {
// 栈顶结点出栈
let node = stack.pop()
list.push(node)
if (node.children && node.children.length) {
// 将候选顶点入栈,进行下一次循环
stack.push(...node.children)
}
}
return list
}
前两个结果为
最后一个结果为