zoukankan      html  css  js  c++  java
  • 用递归处理数据

    var retrunArr = [];
        const arr = [
            ["项目库","餐饮","火锅"],
            ["项目库","餐饮","火大","火锅"],
            ["项目库1","餐饮","火大","火锅"],
            ["项目库1","餐饮","火大","火锅"],
            ["项目库2","餐饮","火大","火锅"],
        ];
    
        
        function di(pushArr, index, strArr) {
            let obj, exist = false;
            obj = {
                name: strArr[index],
                children: index == strArr.length - 1 ? null : []
            }
            pushArr.forEach((o) => {
                if (o.name === strArr[index]) {
                    obj = o;
                    exist = true;
                }
            });
            
            if (!exist) {
                pushArr.push(obj);
            }        
            
            if (index < strArr.length - 1 && obj.children !== null) {
                di(obj.children, index + 1, strArr);
            }
        }
    
        arr.forEach((o, i) => {
            di(retrunArr, 0, arr[i]);
        });
    
    
        console.dir(JSON.stringify(retrunArr));
        /*[
          {
            "name": "项目库",
            "children": [
              {
                "name": "餐饮",
                "children": [
                  {
                    "name": "火锅",
                    "children": null
                  },
                  {
                    "name": "火大",
                    "children": [
                      {
                        "name": "火锅",
                        "children": null
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            "name": "项目库1",
            "children": [
              {
                "name": "餐饮",
                "children": [
                  {
                    "name": "火大",
                    "children": [
                      {
                        "name": "火锅",
                        "children": null
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            "name": "项目库2",
            "children": [
              {
                "name": "餐饮",
                "children": [
                  {
                    "name": "火大",
                    "children": [
                      {
                        "name": "火锅",
                        "children": null
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]*/
  • 相关阅读:
    登录、注册、忘记密码 流程图
    用心每一天,不忘初心,方能走远
    HttpContext.Current.Request.ServerVariables
    Bootstrap实现弹出框和提示框效果代码
    jquery.each()
    js获取页面url
    jquery获取ul中的第一个li
    sql server 取文件名函数 转载
    jquery手风琴
    给母亲的信
  • 原文地址:https://www.cnblogs.com/yghgo/p/8425701.html
Copyright © 2011-2022 走看看