Tree和array之间相互转换

(一)前言
对于大部分网站需求,我们经常会遇到一种需求,将list转为tree结构,或者将tree转为list结构,或者我们在tree结构中查找对于的数据,返回,或者返回顶层到查找级别的list。

(二)将list转为tree
我们一般会在后台数据库设计时候,当我们设计省市县联动时候,一般会在数据库设计唯一索引id,和pid字段,pid关联父级别id,这样当查询出来的数据很可能是类似下面的结构

const data = [
  { id: 1, pid: 0, name: 'no.1' },
  { id: 2, pid: 1, name: 'no.2' },
  { id: 3, pid: 1, name: 'no.3' },
  { id: 4, pid: 1, name: 'no.4' },
  { id: 5, pid: 1, name: 'no.5' },
  { id: 6, pid: 2, name: 'no.6' },
  { id: 7, pid: 2, name: 'no.7' },
  { id: 8, pid: 2, name: 'no.8' },
  { id: 9, pid: 3, name: 'no.9' },
  { id: 10, pid: 3, name: 'no.10' },
  { id: 11, pid: 3, name: 'no.11' },
  { id: 12, pid: 4, name: 'no.12' },
  { id: 13, pid: 4, name: 'no.13' },
  { id: 14, pid: 13, name: 'no.14' },
];

但是实际上大部分UI展示需要生成tree形结构,方便UI暂时,这时候我们应该怎么办呢,你可以写一个arrayToTree方法,类似如下

function arrayToTree(list, pid = 0) {
  return list.filter(item => item.pid === pid).map(item => ({
    ...item,
    children: arrayToTree(list, item.id),
  }));
}

// 调用
console.log(arrayToTree(data));

那么调用和输出结构就如下

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值