Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. function buildTree(nodes) {
  2. var lookup = {};
  3. var tree = [];
  4. nodes.forEach(function (node) {
  5. node.children = [];
  6. lookup[node.id] = node;
  7. });
  8. nodes.forEach(function (node) {
  9. if (node.parentid != null) {
  10. var parent = lookup[node.parentid];
  11. parent.children.push(node);
  12. } else {
  13. tree.push(node);
  14. }
  15. });
  16. console.log(tree);
  17. return tree;
  18. }
  19.  
  20. var test = [{
  21. 'id': 1,
  22. 'parentid': null
  23. }, {
  24. 'id': 2,
  25. 'parentid': 1
  26. }, {
  27. 'id': 3,
  28. 'parentid': 1
  29. }, {
  30. 'id': 4,
  31. 'parentid': 3
  32. }, {
  33. 'id': 5,
  34. 'parentid': null
  35. }, {
  36. 'id': 6,
  37. 'parentid': 5
  38. }];
  39.  
  40. buildTree(test);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement