列表数据转tree(树形)结构数据

调用listToTree方法可以快速将一维列表数据转成树形结构数据

	let list= [
      {
    
    
        id: 1001,
        parentId: "",
        name: "AA",
      },
      {
    
    
        id: 1002,
        parentId: 1001,
        name: "BB",
      },
      {
    
    
        id: 1003,
        parentId: "",
        name: "CC",
      },
      {
    
    
        id: 1004,
        parentId: 1003,
        name: "DD",
      },
      {
    
    
        id: 1005,
        parentId: 1003,
        name: "EE",
      },
      {
    
    
        id: 1006,
        parentId: 1002,
        name: "FF",
      },
      {
    
    
        id: 1007,
        parentId: 1002,
        name: "GG",
      },
      {
    
    
        id: 1008,
        parentId: 1004,
        name: "HH",
      },
      {
    
    
        id: 1009,
        parentId: 1005,
        name: "II",
      },
    ]
    console.log(listToTree(list))
	function listToTree(data) {
    
    
      // * 先生成parent建立父子关系
      const obj = {
    
    };
      data.forEach((item) => {
    
    
        obj[item.id] = item;
      });
      const parentList = [];
      data.forEach((item) => {
    
    
        const parent = obj[item.parentId];
        if (parent) {
    
    
          // * 当前项有父节点
          parent.children = parent.children || [];
          parent.children.push(item);
        } else {
    
    
          // * 当前项没有父节点 -> 顶层
          parentList.push(item);
        }
      });
      return parentList;
    },

猜你喜欢

转载自blog.csdn.net/weixin_47818125/article/details/127343065