最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
js如何实现树形数据转成扁平数据 js实现树形数据转成扁平数据代码
时间:2022-06-29 00:57:32 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下js实现树形数据转成扁平数据代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
利用递归的方法循环树形数组,当遇到有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) // 查看结果
结果:
相关文章
- 致命公司铲子可攻击怪物类型汇总 12-05
- 星球重启20级头盔制作方法详解 12-05
- 星球重启分解废品任务完成方法 12-05
- 星球重启偶像任务攻略 偶像任务过法 12-05
- 星球重启9个酸液腺体获取攻略 12-05
- 星球重启采集工具制作方法 采集工具怎么做 12-05
