分析vban的utlis中的helper方法(2)——树形数组

将列表(数组)转换为树形结构的函数

// tree from list
// 列表中的树
export function listToTree<T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] {
  const conf = getConfig(config) as TreeHelperConfig;
  //nodeMap 是一个 Map,用于存储每个节点的引用,以 id 为键,节点对象为值。
  const nodeMap = new Map();
  const result: T[] = [];
  const { id, children, pid } = conf;

//遍历输入的列表 list,为每个节点初始化 children 字段(如果不存在的话)。
//将每个节点存储到 nodeMap 中,以便后续可以通过 id 快速查找父节点。
  for (const node of list) {
    node[children] = node[children] || [];
    nodeMap.set(node[id], node);
  }
  //再次遍历列表,根据每个节点的 pid 在 nodeMap 中查找其父节点。
  //如果找到了父节点(parent),将当前节点添加到父节点的 children 数组中。
 //如果没有找到父节点(即当前节点是根节点),则将当前节点添加到 result 数组中。
  for (const node of list) {
    const parent = nodeMap.get(node[pid]);
    (parent ? parent[children] : result).push(node);
  }
  return result;
}

示例使用

const list = [
  { id: 1, pid: null, name: 'Root' },
  { id: 2, pid: 1, name: 'Child 1' },
  { id: 3, pid: 1, name: 'Child 2' },
  { id: 4, pid: 2, name: 'Grandchild' }
];

调用结果

[
  {
    id: 1,
    pid: null,
    name: 'Root',
    children: [
      { id: 2, pid: 1, name: 'Child 1', children: [{ id: 4, pid: 2, name: 'Grandchild', children: [] }] },
      { id: 3, pid: 1, name: 'Child 2', children: [] }
    ]
  }
]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值