Skip to content

Instantly share code, notes, and snippets.

@itacirgabral
Created June 8, 2018 21:49
Show Gist options
  • Save itacirgabral/23f791bbceeb0b713bffa98b51948a35 to your computer and use it in GitHub Desktop.
Save itacirgabral/23f791bbceeb0b713bffa98b51948a35 to your computer and use it in GitHub Desktop.
/*
https://www.youtube.com/watch?v=k7-N8R0-KY4&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84
@Gegeg
Could you do this with reduce?
*/
const categories = [
{ id: 'a', parent: '0'},
{ id: 'b', parent: '0'},
{ id: 'c', parent: 'a'},
{ id: 'd', parent: 'a'},
{ id: 'e', parent: 'd'},
{ id: 'f', parent: 'e'},
{ id: 'g', parent: 'f'}
]
const mkTree = id => categories.filter(
e => e.parent === id
).reduce((acc, last) => {
acc[last.id] = mkTree(last.id)
return acc
},{})
console.log(mkTree('0'), null, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment