js实现树形数据转成扁平数据的方法示例实现树形数据转成扁平数据的方法示例
主要介绍了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) // 查看结果
结果:
查看源码
扁平数据转成树形数据,请参考这篇文章:js实现无限层级树形数据结构(创新算法)
js将扁平结构数据转换为树形结构将扁平结构数据转换为树形结构