利用递归的方法循环树形数组,当遇到有children的对象再次调用递归函数循环children数组,每次循环的数据放入一个提前声明好的数组里,等所有递归函数执行完,这个数组即是想要得到的扁平数据数组。
const fn = (source)=>{
let res = []
source.forEach(el=>{
res.push(el)
el.children && res.push(...fn(el.children))
})
return res
}
示例1
// 递归函数
const fn = (source)=>{
let res = []
source.forEach(el=>{
res.push(el)
el.children && res.push(...fn(el.children))
})
return res
}
// 树形数据
const arr = [
{ id: "1", rank: 1 },
{ id: "2", rank: 1,
children:[
{ id: "2.1", rank: 2 },
{ id: "2.2", rank: 2 }
]
},
{ id: "3", rank:1,
children:[
{ id: "3.1", rank:2,
children: [
{ id:'3.1.1', rank:3,
children:[
{ id: "3.1.1.1", rank: 4,
children:[
{ id: "3.1.1.1.1", rank: 5 }
]
}
]
}
]
}
]
}
]
console.log(fn(arr)) // 查看结果
结果:
查看源码
扁平数据转成树形数据,请参考这篇文章:js实现无限层级树形数据结构(创新算法)