Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/bc6c4024952ee48a87eec24ca31c363a to your computer and use it in GitHub Desktop.
Save anonymous/bc6c4024952ee48a87eec24ca31c363a to your computer and use it in GitHub Desktop.
let categories = [
{ id: 'animals', 'parent': null },
{ id: 'mammals', 'parent': 'animals' },
{ id: 'cats', 'parent': 'mammals' },
{ id: 'dogs', 'parent':'mammals' },
{ id: 'chihuahua', 'parent': 'dogs' },
{ id: 'labrador', 'parent': 'dogs' },
{ id: 'persian', 'parent': 'cats' },
{ id: 'siamese', 'parent': 'cats' }
]
let makeTree = (categories, parent = null) => {
let node = {}
categories
.filter(c => c.parent === parent)
.forEach(c =>
node[c.id] = makeTree(categories, c.id))
return node
}
console.log(
JSON.stringify(makeTree(categories), null, 2)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment