js实现tree结构树生成
使用es5 Array.reduce()方法实现
1.语法
2.参数
3.实现代码
1 //树形数据 2 let child = [ 3 { 4 name: "文件1", 5 pid: 1, 6 id: 10001 7 }, 8 { 9 name: "文件2", 10 pid: 1, 11 id: 10002 12 }, 13 { 14 name: "文件2-1", 15 pid: 2, 16 id: 10003 17 }, 18 { 19 name: "文件2-2", 20 pid: 2, 21 id: 10004 22 }, 23 { 24 name: "文件1-1-1", 25 pid: 4, 26 id: 10005 27 }, 28 { 29 name: "文件2-1-1", 30 pid: 5, 31 id: 10006 32 }, 33 ]; 34 let parent = [ 35 { 36 name: "文件夹1", 37 pid: 0, 38 id: 1 39 }, 40 { 41 name: "文件夹2", 42 pid: 0, 43 id: 2 44 }, 45 { 46 name: "文件夹3", 47 pid: 0, 48 id: 3 49 }, 50 { 51 name: "文件夹1-1", 52 pid: 1, 53 id: 4 54 }, 55 { 56 name: "文件夹2-1", 57 pid: 2, 58 id: 5 59 }, 60 ]; 61 let allData = [...child, ...parent]; 62 63 let treeMapList = allData.reduce((prev, current) => { 64 prev[current['id']] = current; 65 return prev; 66 }, {}); 67 68 let result = allData.reduce((arr, current) => { 69 let pid = current.pid; 70 let parent = treeMapList[pid]; 71 if (parent) { 72 parent.children ? parent.children.push(current) : 73 parent.children = [current]; 74 } else if (pid === 0) { 75 arr.push(current); 76 } 77 return arr; 78 }, []);