js將有父子關係的資料轉換成樹形結構資料

龍恩0707發表於2018-07-06

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);

相關文章