美文网首页
一维数组转树形结构

一维数组转树形结构

作者: AcessCors | 来源:发表于2019-05-14 11:40 被阅读0次

    在JavaScript中如何将有父子关系的一维数组转换成树形结构:
    1:首先创建一个有父子结构关系的数组

    let arrList = [
          {id:"1",name:"parentNode1",age:"60",parentKey:'0'},
          {id:"2",name:"parentNode2",age:"60",parentKey:'0'},
          {id:"1_1",name:"Node_1",age:"40",parentKey:'1'},
          {id:"1_2",name:"Node_2",age:"41",parentKey:'1'},
          {id:"1_3",name:"Node_3",age:"42",parentKey:'1'},
          {id:"1_4",name:"Node_4",age:"43",parentKey:'1'},
          {id:"1_1_1",name:"childNode_1",age:"20",parentKey:'1_1'},
          {id:"1_1_2",name:"childNode_2",age:"21",parentKey:'1_1'},
          {id:"1_1_3",name:"childNode_3",age:"22",parentKey:'1_1'},
          {id:"1_2_1",name:"childNode_4",age:"20",parentKey:'1_2'},
          {id:"1_2_2",name:"childNode_5",age:"21",parentKey:'1_2'},
          {id:"1_2_3",name:"childNode_6",age:"22",parentKey:'1_2'},
          {id:"1_3_1",name:"childNode_7",age:"20",parentKey:'1_3'},
          {id:"1_3_2",name:"childNode_8",age:"21",parentKey:'1_3'},
          {id:"1_3_3",name:"childNode_9",age:"22",parentKey:'1_3'},
     ];
    

    2:将数组传入格式化的方法(这里要注意parentKey,id,children三个属性)

     function formatArrToTree(arrList){
            //  将没有父节点的元素分离
            let parents = arrList.filter(value => value.parentKey === '0' || value.parentKey === null);
            let children = arrList.filter(value => value.parentKey !== '0' && value.parentKey !== null);
            //  定义遍历的方法 
            let translator = (parents, children) => {
              //  遍历父节点的数组
              parents.forEach((parent) => {
              //  遍历子节点的数组
                children.forEach((current, index) => {
                  //  找到父节点对应的子节点
                  if (current.parentKey === parent.id) {
                     // 对子节点数据进行深复制,这里只支持部分类型的数据深复制
                    let temp = JSON.parse(JSON.stringify(children));
                    //  从temp中移除当前节点,减少递归
                    temp.splice(index, 1);
                    //  让当前子节点作为唯一的父节点,去递归查找其对应的子节点
                    translator([current], temp);
                    //  把找到子节点放入父节点的children属性中
                    typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current];
                  }
                })
              })
            }
            //  调用转换方法
            translator(parents, children);
            return parents;
          }
          console.log(formatArrToTree(arrList));
    

    相关文章

      网友评论

          本文标题:一维数组转树形结构

          本文链接:https://www.haomeiwen.com/subject/lhtsaqtx.html