Created
April 29, 2020 15:23
-
-
Save elvishp2006/e304d9a775867498ecfe8d79c6e21817 to your computer and use it in GitHub Desktop.
Create nested collection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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