1. <!doctype html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="Generator" content="EditPlus®">
    6. <meta name="Author" content="">
    7. <meta name="Keywords" content="">
    8. <meta name="Description" content="">
    9. <title>将id pid的转成children格式的</title>
    10. </head>
    11. <body>
    12. <script type="text/javascript">
    13. var nodes = [
    14. {id:73, pId:0,treeCode:73, treePCode:0, name: "父节点1"},
    15. {id:7301, pId:73,treeCode:7301, treePCode:73, name: "子节点1"},
    16. {id:73011, pId:7301,treeCode:73011, treePCode:7301, name: "子节点1"},
    17. {id:73012, pId:7301, treeCode:73012, treePCode:7301,name: "子节点1"},
    18. {id:7302, pId:73, treeCode:7302, treePCode:73,name: "子节点1"},
    19. {id:73021, pId:7302,treeCode:73021, treePCode:7302, name: "子节点1"},
    20. {id:73022, pId:7302,treeCode:73022, treePCode:7302, name: "子节点1"}
    21. ];
    22. window.onload=function(){
    23. var mm=listToTree(nodes);
    24. console.log(mm)
    25. }
    26. function listToTree(data, options) {
    27. if (data && data.length) {
    28. options = options || {}
    29. let ID_KEY = options.idKey || 'id'
    30. let PARENT_KEY = options.parentKey || 'pId'
    31. let CHILDREN_KEY = options.childrenKey || 'children'
    32. let tree = []
    33. let childrenOf = {}
    34. var item, id, parentId
    35. for (var i = 0, length = data.length; i < length; i++) {
    36. item = data[i]
    37. id = item[ID_KEY]
    38. parentId = item[PARENT_KEY] || 0
    39. // 每行数据都可能存在子类
    40. childrenOf[id] = childrenOf[id] || []
    41. // 初始化子类
    42. item[CHILDREN_KEY] = childrenOf[id]
    43. if (parentId != 0) {
    44. // 初始化其父的子节点
    45. childrenOf[parentId] = childrenOf[parentId] || []
    46. // 把它推到父类下的children
    47. childrenOf[parentId].push(item)
    48. } else {
    49. tree.push(item)
    50. }
    51. }
    52. return tree
    53. } else {
    54. return []
    55. }
    56. }
    57. </script>
    58. </body>
    59. </html>