Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. const nest = (items, id = null, link = "parent_id") =>
  2. items
  3. .filter(item => item[link] === id)
  4. .map(item => ({ ...item, children: nest(items, item.id) }))
  5.  
  6. const comments = [
  7. { id: 1, parent_id: null, text: "First reply to post." },
  8. { id: 2, parent_id: 1, text: "First reply to comment #1." },
  9. { id: 3, parent_id: 1, text: "Second reply to comment #1." },
  10. { id: 4, parent_id: 3, text: "First reply to comment #3." },
  11. { id: 5, parent_id: 4, text: "First reply to comment #4." },
  12. { id: 6, parent_id: null, text: "Second reply to post." }
  13. ]
  14.  
  15. nest(comments)
  16. /*
  17. [
  18. { id: 1, parent_id: null, text: "First reply to post.", children: [...] },
  19. { id: 6, parent_id: null, text: "Second reply to post.", children: [] }
  20. ]
  21. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement