js实现树形数据转成扁平数据

mac2024-03-29  30

利用递归的方法循环树形数组,当遇到有children的对象再次调用递归函数循环children数组,每次循环的数据放入一个提前声明好的数组里,等所有递归函数执行完,这个数组即是想要得到的扁平数据数组。

let res = [] const fn = (source)=>{ source.forEach(el=>{ res.push(el) el.children && el.children.length>0 ? fn(el.children) : "" }) }

示例1

let res = [] // 用于存储递归结果(扁平数据) // 递归函数 const fn = (source)=>{ source.forEach(el=>{ res.push(el) el.children && el.children.length>0 ? fn(el.children) : "" // 子级递归 }) } // 树形数据 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 } ] } ] } ] } ] } ] fn(arr) // 执行递归函数 console.log(res) // 查看结果

结果:

查看源码 

扁平数据转成树形数据,请参考这篇文章:js实现无限层级树形数据结构(创新算法)

最新回复(0)