Skip to content

Instantly share code, notes, and snippets.

@ZhihaoLau
Created October 12, 2016 02:41
Show Gist options
  • Save ZhihaoLau/4bf8c836332085198a899556ddd24059 to your computer and use it in GitHub Desktop.
Save ZhihaoLau/4bf8c836332085198a899556ddd24059 to your computer and use it in GitHub Desktop.
recursion.js
let categories = [
{ id: 'animals', 'parent': null },
{ id: 'mammals', 'parent': 'animals' },
{ id: 'cats', 'parent': 'mammals' },
{ id: 'dogs', 'parent': 'mammals' },
{ id: 'chihuahua', 'parent': 'dogs' },
{ id: 'persian', 'parent': 'cats' },
{ id: 'siamese', 'parent': 'cats' },
]
function makeTree(categories, parent) {
let node = {}
categories
.filter(x => x.parent === parent)
.forEach(x => node[x.id] = makeTree(categories, x.id))
return node
}
let tree = makeTree(categories, null)
console.log(
JSON.stringify(tree, null, 2)
)
// outputs:
// ##############################
// {
// "animals": {
// "mammals": {
// "cats": {
// "persian": {},
// "siamese": {}
// },
// "dogs": {
// "chihuahua": {}
// }
// }
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment