以下是一个使用 TypeScript 实现的将数组转化为树的例子:

interface TreeNode {
  id: number;
  name: string;
  children?: TreeNode[];
}

function arrayToTree(arr: TreeNode[]): TreeNode[] {
  const map: { [key: number]: TreeNode } = {};
  const result: TreeNode[] = [];

  // 将节点按照id存储在map中
  arr.forEach(node => {
    map[node.id] = node;
  });

  arr.forEach(node => {
    if (node.children) {
      node.children = node.children.map(childId => map[childId]);
    }
    // 如果节点没有父节点,将其添加到结果中
    if (!node.hasOwnProperty("parentId")) {
      result.push(node);
    } else {
      // 如果节点有父节点,将其作为子节点添加到父节点下
      const parent = map[node.parentId];
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(node);
    }
  });

  return result;
}

// 示例数据
const arr: TreeNode[] = [
  { id: 1, name: "Node 1" },
  { id: 2, name: "Node 2", parentId: 1 },
  { id: 3, name: "Node 3", parentId: 1 },
  { id: 4, name: "Node 4", parentId: 2 },
  { id: 5, name: "Node 5", parentId: 2 },
  { id: 6, name: "Node 6", parentId: 3 },
  { id: 7, name: "Node 7", parentId: 3 },
];

const tree = arrayToTree(arr);
console.log(tree);

这个例子中,我们定义了一个 TreeNode 接口表示树节点的结构。然后,我们定义了一个 arrayToTree 函数,接收一个数组参数,返回转化后的树结构。

arrayToTree 函数中,我们首先使用一个 map 对象将节点按照 id 存储起来,方便后续查找和关联。然后,我们遍历数组中的每个节点,如果节点有子节点,将其子节点转化为对应的节点对象,并将其赋值给节点的 children 属性。如果节点没有父节点,将其添加到结果数组中;如果节点有父节点,将其作为子节点添加到父节点的 children 属性中。

最后,我们使用示例数据调用 arrayToTree 函数,并将转化后的树结构打印到控制台上

給我一個typescript 數組轉樹的可用例子

原文地址: http://www.cveoy.top/t/topic/hXHN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录