当前位置:   article > 正文

js实现树形数据转成扁平数据_后端返回的树数据只要有2级就开始平铺,如果1级孩子时空或者null也针对进行平铺 js

后端返回的树数据只要有2级就开始平铺,如果1级孩子时空或者null也针对进行平铺 js

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

  1. const fn = (source)=>{
  2. let res = []
  3. source.forEach(el=>{
  4. res.push(el)
  5. el.children && res.push(...fn(el.children))
  6. })
  7. return res
  8. }

示例1

  1. // 递归函数
  2. const fn = (source)=>{
  3. let res = []
  4. source.forEach(el=>{
  5. res.push(el)
  6. el.children && res.push(...fn(el.children))
  7. })
  8. return res
  9. }
  10. // 树形数据
  11. const arr = [
  12. { id: "1", rank: 1 },
  13. { id: "2", rank: 1,
  14. children:[
  15. { id: "2.1", rank: 2 },
  16. { id: "2.2", rank: 2 }
  17. ]
  18. },
  19. { id: "3", rank:1,
  20. children:[
  21. { id: "3.1", rank:2,
  22. children: [
  23. { id:'3.1.1', rank:3,
  24. children:[
  25. { id: "3.1.1.1", rank: 4,
  26. children:[
  27. { id: "3.1.1.1.1", rank: 5 }
  28. ]
  29. }
  30. ]
  31. }
  32. ]
  33. }
  34. ]
  35. }
  36. ]
  37. console.log(fn(arr)) // 查看结果

结果:

查看源码 

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/901109
推荐阅读
相关标签
  

闽ICP备14008679号