用递归处理数据

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

 

posted @ 2018-02-07 11:12  天色已晚2016  阅读(181)  评论(0编辑  收藏  举报