1 | export default function array2Tree(nodes, option = {}) {
|
2 | const id = option.id || "id";
|
3 | const pid = option.pid || "pid";
|
4 | const children = option.children || "children";
|
5 | const map = option.map;
|
6 |
|
7 | const result = [];
|
8 | const byIds = {};
|
9 | const len = nodes.length;
|
10 |
|
11 | for (let i = 0; i < len; i++) {
|
12 | if (map) {
|
13 | nodes[i] = map(nodes[i]);
|
14 | }
|
15 | byIds[nodes[i][id]] = nodes[i];
|
16 | }
|
17 |
|
18 | for (let i = 0; i < len; i++) {
|
19 | let parent = byIds[nodes[i][pid]];
|
20 | if (!parent) {
|
21 | result.push(nodes[i]);
|
22 | } else {
|
23 | if (!parent[children]) {
|
24 | parent[children] = [];
|
25 | }
|
26 | parent[children].push(nodes[i]);
|
27 | }
|
28 | }
|
29 |
|
30 | return result;
|
31 | }
|