码迷,mamicode.com
首页 > 其他好文 > 详细

用递归处理数据

时间:2018-02-07 15:03:43      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:nbsp   ==   name   amp   gpo   false   dir   length   post   

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
                  }
                ]
              }
            ]
          }
        ]
      }
    ]*/

 

用递归处理数据

标签:nbsp   ==   name   amp   gpo   false   dir   length   post   

原文地址:https://www.cnblogs.com/yghgo/p/8425701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!