代码改变世界

js将有父子关系的数据转换成树形结构数据

2018-07-06 23:48  龙恩0707  阅读(7062)  评论(0编辑  收藏  举报

js将有父子关系的数据转换成树形结构数据

比如如下基本数据:

let allDatas = [
  {
    id: 3,
    name: 'bbbb',
    parendId: 1
  },
  {
    id: 2,
    name: 'aaaaa',
    parendId: 2
  },
  {
    id: 4,
    name: 'ccccc',
    parendId: 1
  },
  {
    id: 5,
    name: 'ddddd',
    parendId: 4
  },
  {
    id: 6,
    name: 'eeeee',
    parendId: 4
  }, 
  {
    id: 7,
    name: 'ffff',
    parendId: 6
  },
  {
    id: 8,
    name: 'ggggg',
    parendId: 3
  },
  {
    id: 9,
    name: 'hhhhh',
    parendId: 5
  },
  {
    id: 10,
    name: 'jjjj',
    parendId: 6
  }
];

需要转换成如下数据格式,如下:

[
  {
    "id": 3,
    "name": "bbbb",
    "children": [
      {
        "id": 8,
        "name": "ggggg",
        "children": []
      }
    ]
  }, 
  {
    "id": 4,
    "name": "ccccc",
    "children": [
      {
        "id": 5,
        "name": "ddddd",
        "children": [
          {
            "id": 9,
            "name": "hhhhh",
            "children": []
          }
        ]
      }, 
      {
        "id": 6,
        "name": "eeeee",
        "children": [
          {
            "id": 7,
            "name": "ffff",
            "children": []
          }, 
          {
            "id": 10,
            "name": "jjjj",
            "children": []
          }
        ]
      }
    ]
  }
]

如上id为8的父节点就是id为3的,而id为3的父节点为1,但是父节点目前没有,所以id为3就是顶级节点了。同理其他的也是一样的道理;

JS代码如下:

// 属性配置设置
let attr = {
  id: 'id',
  parendId: 'parendId',
  name: 'name',
  rootId: 1
};
function toTreeData(data, attr) {
  let tree = [];
  let resData = data;
  for (let i = 0; i < resData.length; i++) {
    if (resData[i].parendId === attr.rootId) {
      let obj = {
        id: resData[i][attr.id],
        name: resData[i][attr.name],
        children: []
      };
      tree.push(obj);
      resData.splice(i, 1);
      i--;
    }
  }
  var run = function(treeArrs) {
    if (resData.length > 0) {
      for (let i = 0; i < treeArrs.length; i++) {
        for (let j = 0; j < resData.length; j++) {
          if (treeArrs[i].id === resData[j][attr.parendId]) {
            let obj = {
              id: resData[j][attr.id],
              name: resData[j][attr.name],
              children: []
            };
            treeArrs[i].children.push(obj);
            resData.splice(j, 1);
            j--;
          }
        }
        run(treeArrs[i].children);
      }
    }
  };
  run(tree);
  return tree;
}
let arr = toTreeData(allDatas, attr);
console.log(arr);