数组转Tree结构,非递归的方法

// 把下面例子中平铺的数组包对象的数据转成树形结构

//[
//   { id: '01', pid: '', name: '老王', children: [] },
//   { id: '02', pid: '01', name: '小王', children: [] },
//   { id: '03', pid: '02', name: '小小王', children: [] },
//   { id: '04', pid: '', name: '小张', children: [] },
//   { id: '05', pid: '04', name: '小小张', children: [] }
// ]


export function tranListToTreeData(arr) {

  // 最终要展示的树形结构newArr

  const newArr = []

  // 把所有数据都放到对象中

  const map = {}

  arr.forEach(item => {

    // 给每一项添加children

    item.children = []

    // 构建字典,字典的键是arr每一项的id;值是arr的每一项

    map[item.id] = item

    // 这个对象里的数据是这样的,pid就是父级的id,例如:老王没有pid,他就没有父级;
    // 小王的pid是'01'对应老王的id也是'01',说明小王是老王的children
    // {"01":{id: '01', pid: '', name: '老王',children:
    // [{ id: '02', pid: '01', name: '小王', children: 
    // [{ id: '03', pid: '02', name: '小小王', children: [] }]}]},
    // {"02":{ id: '04', pid: '', name: '小张', children: 
    // [{ id: '05', pid: '04', name: '小小张', children: [] }] }},

 })

  // 2.让每一项找它的父级

  arr.forEach(item => {

    // 声明parent是父级

    const parent = map[item.pid]

    parent ? parent.children.push(item) : newArr.push(item)
  })
  return newArr
}


//3.在main.js中导入模块,在控制台输出,验证你的结果

import { tranListToTreeData } from '@/utils/tree'

const list = [
  { id: '01', pid: '', name: '老王', children: [] },
  { id: '02', pid: '01', name: '小王', children: [] },
  { id: '03', pid: '01', name: '小小王', children: [] },
  { id: '04', pid: '02', name: '小张', children: [] },
  { id: '05', pid: '04', name: '小小张', children: [] }
]

console.log('数组', tranListToTreeData(list))


 

 这是在vue的项目中,用ES6的语法,模块导入导出,在普通js文件中直接导入这个函数,传入简单的数组包对象即可

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值