[JavaScript]将数组按照parentId和id整理成树状结构

 JavaScript

function arrayToTree(items) {
    const rootItems = [];
    const lookup = {};
 
    for (const item of items) {
        const itemId = item.id;
        lookup[itemId] = item;
        const parentId = item.parentId;
        if (parentId === null) {
            rootItems.push(item);
            continue;
        }
        const parent = lookup[parentId];
        if (parent) {
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(item);
        }
    }
    return rootItems;
}
 
// 示例数据
const items = [
    { id: 1, parentId: null },
    { id: 2, parentId: 1 },
    { id: 3, parentId: 1 },
    { id: 4, parentId: 2 },
    { id: 5, parentId: 3 },
    { id: 6, parentId: 4 },
    { id: 7, parentId: 6 },
    { id: 8, parentId: 7 }
];
 
// 使用函数转换成树状结构
const tree = arrayToTree(items);
console.log(tree);

 

TypeScript

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

const data: TreeNode[] = [
  { id: 1, parentId: null, name: 'Root 1' },
  { id: 2, parentId: 1, name: 'Child 1.1' },
  { id: 3, parentId: 1, name: 'Child 1.2' },
  { id: 4, parentId: 2, name: 'Child 1.1.1' },
  { id: 5, parentId: null, name: 'Root 2' },
  { id: 6, parentId: 5, name: 'Child 2.1' }
];

function buildTree(data: TreeNode[]): TreeNode[] {
  // 初始化一个数据字典,方便查找
  const dataDictionary: { [key: number]: TreeNode & { children: TreeNode[] } } = data.reduce((acc, item) => {
    acc[item.id] = { ...item, children: [] };
    return acc;
  }, {} as { [key: number]: TreeNode & { children: TreeNode[] } });

  // 构建树结构
  const tree: TreeNode[] = [];

  data.forEach(item => {
    if (item.parentId === null) {
      // 根节点,加入树结构的根数组
      tree.push(dataDictionary[item.id]);
    } else {
      // 子节点,找到父节点并加入其children数组
      if (dataDictionary[item.parentId]) {
        dataDictionary[item.parentId].children.push(dataDictionary[item.id]);
      }
    }
  });

  return tree;
}

const treeData = buildTree(data);
console.log(JSON.stringify(treeData, null, 2));

 

posted @ 2024-11-18 15:22  夕苜19  阅读(22)  评论(0编辑  收藏  举报