js实现el-tree树形数据转为扁平数据
对于上一篇文章 vue中的递归做出 一些改进

element=========截图

解决方法:
利用递归的方法循环树形数据,当遇到有children的对象再次强调有递归函数循环children数组,每次循环的数据放入一个提前生命好的数组里,等所有的递归函数执行完毕,这个数据就是想要的扁平数据数组,如上图。
let res = [] // 用于存储递归结果(扁平数据)
// 递归函数
const fn = (source)=>{
source.forEach(el=>{
res.push(el)
el.child && el.child.length>0 ? fn(el.child) : "" // 子级递归
})
}
示例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) // 查看结果
结果


浙公网安备 33010602011771号