Guest User

Untitled

a guest
Oct 18th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. const arr = [
  2. { id: 1, parentid: 0 },
  3. { id: 4, parentid: 2 },
  4. { id: 3, parentid: 1 },
  5. { id: 5, parentid: 0 },
  6. { id: 6, parentid: 0 },
  7. { id: 2, parentid: 1 },
  8. { id: 7, parentid: 4 },
  9. { id: 8, parentid: 1 },
  10. { id: 9, parentid: 7 },
  11. { id: 10, parentid: 9 },
  12. { id: 11, parentid: 3 }
  13. ];
  14.  
  15. function unflatten(arr) {
  16. const map = arr.reduce((pre, item) => {
  17. pre[item.id] = item;
  18. pre[item.id].children = [];
  19. return pre;
  20. }, {});
  21.  
  22. const tree = [];
  23. Object.keys(map).forEach(id => {
  24. const value = map[id];
  25. if (value.parentid) {
  26. map[value.parentid].children.push(value);
  27. } else {
  28. tree.push(value);
  29. }
  30. });
  31. return tree;
  32. }
  33.  
  34. const tree = unflatten(arr);
Add Comment
Please, Sign In to add comment