Skip to content

Instantly share code, notes, and snippets.

@elvishp2006
Created April 29, 2020 15:23
Show Gist options
  • Save elvishp2006/e304d9a775867498ecfe8d79c6e21817 to your computer and use it in GitHub Desktop.
Save elvishp2006/e304d9a775867498ecfe8d79c6e21817 to your computer and use it in GitHub Desktop.
Create nested collection.
// Data Set
// One top level comment
const comments = [{
id: 1,
parent_id: null
}, {
id: 2,
parent_id: 1
}, {
id: 3,
parent_id: 1
}, {
id: 4,
parent_id: 2
}, {
id: 5,
parent_id: 4
}];
const nest = (items, id = null, link = 'parent_id') =>
items
.filter(item => item[link] === id)
.map(item => ({ ...item, children: nest(items, item.id) }));
console.log(
nest(comments)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment