1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| console.time() var nodes = [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", }, { "id": "13", "parentId": "12", "text": "Man", "level": "1", }, { "id": "14", "parentId": "13", "text": "Man", "level": "1", }, { "id": "15", "parentId": "15", "text": "Man", "level": "1", }, { "id": "16", "parentId": "12", "text": "Man", "level": "1", },]; var map = {}, node, roots = []; for (var i = 0; i < nodes.length; i += 1) { node = nodes[i]; node.children = []; map[node.id] = i; if (node.parentId !== "0") { nodes[map[node.parentId]].children.push(node); } else { roots.push(node); } } console.timeEnd(); console.log(roots);
|