数据格式转换,类listjson转换为类树的json数据

1.原始数据
数据结构为一个二维表list存的树:

    [json1,json2...]
    json的格式为:
    {id,name,...deptPreId(树节点)}

原始数据例子

 [{"id":1,"deptName":"B","deptFullname":"A_B","deptLevel":2,"deptPreId":2,},

     {"id":2,"deptName":"A","deptFullname":null,"deptLevel":1,"deptPreId":null,},

     {"id":3,"deptName":"C","deptFullname":null,"deptLevel":3,"deptPreId":1,},

    {"id":4,"deptName":"wwxxX","deptFullname":null,"deptLevel":null,"deptPreId":1},

     {"id":5,"deptName":"123124124","deptFullname":null,"deptLevel"2,"deptPreId":1}

    ];

2.目标数据:

将其转换为下面目标数据,也是一个类似的树,有树形层次:
数据格式如下:

  list:[json1,json2]
  json:{json,childList}
  Childlist:[json1,json2]

目标数据例子:

data=[
    {"id":2,"deptName":"A","deptFullname":null,"deptLevel":1,"deptPreId":null
    ,
    Child:
      [
        {"id":1,"deptName":"B","deptFullname":"A_B","deptLevel":2,"deptPreId":2,
        Child:
            [
            {"id":3,"deptName":"C","deptFullname":null,"deptLevel":3,"deptPreId":1,}
            ]
         },
        {"id":5,"deptName":"123124124","deptFullname":null,"deptLevel"2,"deptPreId":1}
    ]
}]
阅读 2.8k
1 个回答

用一个函数解决了这个问题,其中指定deptPreId不存在时为父向下查询:

function listToTree(data,startCon=null,id='id',pid='parenId',child='child') {
    let parents = data.filter(value => !value[pid]);
    if(startCon)
    {
        parents=startCon;
    }
    let children = data.filter(value => value[pid] !== 0);
    let translator = (parents, children) => {
        parents.forEach(parent => {
            children.forEach((current, index) => {
                if (current[pid] === parent[id]) {
                    let temp = JSON.parse(JSON.stringify(children));
                    temp.splice(index, 1);
                    translator([current], temp);
                    typeof parent[child] !== 'undefined'
                        ? parent[child].push(current)
                        : (parent[child] = [current]);
                }
            })
        })
    };

    translator(parents, children);

    return parents;
}
推荐问题