Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. const data = [{id: 3, p_id: 2}, {id: 4, p_id: 1}, {id: 1, p_id: null}, {id: 5, p_id: 2}, {id: 2, p_id: 1}, {id: 6, p_id: 2}];
  2.  
  3. const treeData = [];
  4.  
  5. function buildTree(data, treeData) {
  6. const findInChildren = (parent, obj) => {
  7. if (parent.children) {
  8. const childParentIndex = parent.children.findIndex((o) => o.id === obj.p_id);
  9. if (childParentIndex > -1) {
  10. if (!parent.children[childParentIndex].children) {
  11. parent.children[childParentIndex].children = [];
  12. }
  13. parent.children[childParentIndex].children.push(obj);
  14. } else {
  15. for (let ci=0; ci<parent.children.length; ci++) {
  16. return findInChildren(parent.children[ci], obj);
  17. }
  18. }
  19. } else {
  20. data.push(obj);
  21. }
  22. return;
  23. }
  24. for (let i=0; i<data.length; i++) {
  25. if (!data[i].p_id) {
  26. treeData.push(data[i]);
  27. } else {
  28. const parentIndex = treeData.findIndex((o) => o.id === data[i].p_id);
  29. if (parentIndex > -1) {
  30. if (!treeData[parentIndex].children) {
  31. treeData[parentIndex].children = [];
  32. }
  33. treeData[parentIndex].children.push(data[i]);
  34. } else {
  35. if (!treeData.length) {
  36. data.push(data[i]);
  37. } else {
  38. for (let ti=0; ti<treeData.length; ti++) {
  39. findInChildren(treeData[ti], data[i]);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. return treeData;
  46. }
  47.  
  48. const result = buildTree(data, treeData);
  49.  
  50. console.log(result);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement