| 373 | }; |
| 374 | |
| 375 | function flatToTree(flatArr, idKey, pIdKey, childrenKey, rootPid) { |
| 376 | idKey = idKey || 'id'; |
| 377 | pIdKey = pIdKey || 'parentId'; |
| 378 | childrenKey = childrenKey || 'children'; |
| 379 | // 创建一个空的 map 对象,用于保存所有的节点 |
| 380 | var map = {}; |
| 381 | var rootNodes = []; |
| 382 | |
| 383 | var idTemp = ''; |
| 384 | var pidTemp = ''; |
| 385 | layui.each(flatArr, function (index, item) { |
| 386 | idTemp = idKey + item[idKey]; |
| 387 | pidTemp = idKey + item[pIdKey]; |
| 388 | |
| 389 | // 将节点存入 map 对象 |
| 390 | if (!map[idTemp]) { |
| 391 | map[idTemp] = {}; |
| 392 | map[idTemp][childrenKey] = []; |
| 393 | } |
| 394 | |
| 395 | // 合并节点 |
| 396 | var tempObj = {}; |
| 397 | tempObj[childrenKey] = map[idTemp][childrenKey]; |
| 398 | map[idTemp] = $.extend({}, item, tempObj); |
| 399 | |
| 400 | var isRootNode = rootPid |
| 401 | ? map[idTemp][pIdKey] === rootPid |
| 402 | : !map[idTemp][pIdKey]; |
| 403 | if (isRootNode) { |
| 404 | rootNodes.push(map[idTemp]); |
| 405 | } else { |
| 406 | if (!map[pidTemp]) { |
| 407 | map[pidTemp] = {}; |
| 408 | map[pidTemp][childrenKey] = []; |
| 409 | } |
| 410 | map[pidTemp][childrenKey].push(map[idTemp]); |
| 411 | } |
| 412 | }); |
| 413 | |
| 414 | return rootNodes; |
| 415 | } |
| 416 | |
| 417 | Class.prototype.flatToTree = function (tableData) { |
| 418 | var that = this; |