js工具函数-扁平数组与树结构数组相互转换

迈不过友情╰ 2024-04-01 14:17 132阅读 0赞
  1. /** 扁平数组转树结构数组 */
  2. export function dealArrayToTree(arr, id = "id", parentid = "parentid") {
  3. function arrayToTree(items) {
  4. const result = []
  5. const itemMap = {
  6. }
  7. for (const item of items) {
  8. const ID = item[id]
  9. const PARENTID = item[parentid]
  10. if (!itemMap[ID]) {
  11. itemMap[ID] = {
  12. children: [],
  13. }
  14. }
  15. itemMap[ID] = {
  16. ...item,
  17. children: itemMap[ID]['children'],
  18. }
  19. const treeItem = itemMap[ID]
  20. // 这里后端返回数据的最上级父节点id是-1,根据个人数据做改定,比如判断0,null,undefined
  21. if (PARENTID === "-1") {
  22. result.push(treeItem)
  23. } else {
  24. if (!itemMap[PARENTID]) {
  25. itemMap[PARENTID] = {
  26. children: [],
  27. }
  28. }
  29. itemMap[PARENTID].children.push(treeItem)
  30. }
  31. }
  32. return result
  33. }
  34. return arrayToTree(arr)
  35. }
  36. /** 树结构数组转扁平数组 */
  37. export function treeToArray(tree) {
  38. const arr = []
  39. function recursiveFunction(tree) {
  40. for (let i = 0; i < tree.length; i++) {
  41. arr.push(tree[i])
  42. if (tree[i].children && tree[i].children.length) {
  43. recursiveFunction(tree[i].children)
  44. }
  45. }
  46. }
  47. recursiveFunction(tree)
  48. return arr
  49. }

发表评论

表情:
评论列表 (有 0 条评论,132人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JS数组扁平

    一道笔试题,将一个嵌套数组扁平化处理。   ▍题目 > 将\[1,2,\[3,\[4,5\]\]\]转化成\[1,2,3,4,5\]。   ▍方法一:递归

    相关 js 数组扁平

    第一种 > 依次把每一项添加进新数组 > 如果为非数组,直接添加 > 如果为数组,则添加递归操作的结果 function flatten(ar