将扁平结构转换为树形结构:JS和TS实现

前端 2023-04-04

将扁平结构转换为树形结构

在前端开发的过程中免不了要处理各种展示树结构的场景,后端往往是返回一整个列表让前自己处理,这里我基于 JS 和 TS 分别实现了此功能

JavaScript

const sourceList = [
  { id: 1, name: 'A', parent_id: null },
  { id: 2, name: 'B', parent_id: 1 },
  { id: 3, name: 'C', parent_id: 1 },
  { id: 4, name: 'D', parent_id: 2 },
  { id: 5, name: 'E', parent_id: 2 },
  { id: 6, name: 'F', parent_id: 3 },
];

function buildTree(sourceList, parent_id = null) {
  const treeList = [];
  for (const item of sourceList) {
    if (parent_id === item.parent_id) {
      const childNode = { ...item };
      const childrenNodes = buildTree(sourceList, item.id);
      if (childrenNodes.length > 0) {
        childNode.children = childrenNodes;
      }
      treeList.push(childNode);
    }
  }
  return treeList;
}

const tree = buildTree(sourceList);
console.log(tree);

a

<br/>

<br/>

TypeScript

interface Node {
  id: number;
  name: string;
  parent_id: number | null;
  children?: Node[];
}

const sourceList: Node[] = [
  { id: 1, name: 'A', parent_id: null },
  { id: 2, name: 'B', parent_id: 1 },
  { id: 3, name: 'C', parent_id: 1 },
  { id: 4, name: 'D', parent_id: 2 },
  { id: 5, name: 'E', parent_id: 2 },
  { id: 6, name: 'F', parent_id: 3 },
];

function buildTree(sourceList: Node[], parent_id: number | null = null): Node[] {
  const treeList: Node[] = [];
  for (const item of sourceList) {
    if (parent_id === item.parent_id) {
      const childNode: Node = { ...item };
      const childrenNodes = buildTree(sourceList, item.id);
      if (childrenNodes.length > 0) {
        childNode.children = childrenNodes;
      }
      treeList.push(childNode);
    }
  }
  return treeList;
}

const tree = buildTree(sourceList);
console.log(tree);