this-way 2022-10-17 11:44 采纳率: 0%
浏览 16

普通数组 怎么 转成多叉树

{nettypeL"4G",name:"CQT",temp:"测试项一"},
{nettypeL"4G",name:"CQT",temp:"测试项二"},
{nettypeL"4G",name:"CQT",temp:"测试项三"},
{nettypeL"4G",name:"CYZ",temp:"测试项一"},
{nettypeL"4G",name:"NEYT",temp:"测试项一"},
{nettypeL"4G",name:"NEYT",temp:"测试项二"},
{nettypeL"4G",name:"CC",temp:"测试项一"},
{nettypeL"5G",name:"CA",temp:"测试项一"},
{nettypeL"5G",name:"QQPO",temp:"测试项一"},
{nettypeL"5G",name:"NEYT",temp:"测试项一"},
{nettypeL"5G",name:"NEYT",temp:"测试项二"},

这种结构怎么转成

{
  id:"root",
  value: {name: "测试项“,level: 1},
  children: [
    { id:"4G",  value: {name: "4G“,level: 2},
      children: [
        { id:"CQT", value: {name: "CQT“,level: 3}, children: [....], },
        {...}
      ],
    },
    { id:"5G", value: {name: "5G“,level: 2},
      children: [
        { id:"CA", value: {name: "CA“,level: 3}, children: [....], },
        {....}
      ],
    }
  ],
},

  • 写回答

1条回答 默认 最新

  • Iam_楠 前端领域新星创作者 2022-10-17 12:13
    关注
        const array = [
          { id: 1, parentId: 0, name: "菜单1" },
          { id: 2, parentId: 0, name: "菜单2" },
          { id: 3, parentId: 0, name: "菜单3" },
          { id: 4, parentId: 1, name: "菜单4" },
          { id: 5, parentId: 1, name: "菜单5" },
          { id: 6, parentId: 2, name: "菜单6" },
          { id: 7, parentId: 4, name: "菜单7" },
          { id: 8, parentId: 7, name: "菜单8" },
          { id: 9, parentId: 8, name: "菜单9" },
          { id: 10, parentId: 9, name: "菜单10" },
          { id: 11, parentId: 10, name: "菜单11" },
          { id: 12, parentId: 11, name: "菜单12" },
          { id: 13, parentId: 12, name: "菜单13" },
          { id: 14, parentId: 13, name: "菜单14" },
        ];
    
    /**
     * 方法二:递归实现
     * @param { Array } list 数组
     * @param { String } parentId 父级 id
     * @param { Object } param2 可配置参数
     */
     
    const generateTree = (
      list,
      parentId = 0,
      { idName = "id", parentIdName = "parentId", childName = "children" } = {}
    ) => {
      if (!Array.isArray(list)) {
        throw new Error("type only Array");
        // new Error("type only Array");
        return list;
      }
      return list.reduce((pre, cur) => {
        // 找到parentId 的子节点之后,递归找子节点的下一级节点
        if (cur[parentIdName] === parentId) {
          const children = generateTree(list, cur[idName]);
          if (children?.length) {
            cur[childName] = children;
          }
          return [...pre, cur];
        }
        return pre;
      }, []);
    };
    const result = generateTree(array, 0);
     
     
    
    评论

报告相同问题?

问题事件

  • 创建了问题 10月17日

悬赏问题

  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。