Skip to content

Instantly share code, notes, and snippets.

@SakoMe
Created September 21, 2017 05:27
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 SakoMe/4aab46c331941f6a904d174668e1cb11 to your computer and use it in GitHub Desktop.
Save SakoMe/4aab46c331941f6a904d174668e1cb11 to your computer and use it in GitHub Desktop.
Taking an array of objects and representing as a tree using recursion
// Basic Recursion
const countDownFrom = (num) => {
if (num === 0) return
console.log(num)
countDownFrom(num - 1)
}
countDownFrom(10)
// Practical example. Taking data from a realtional database to make a "windows style menu"
const 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' }
]
const makeTree = (categories, parent) => {
const 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)
, null, 2)
)
// Desired output - tree structure:
{
animals: {
mamals: {
dogs: {
chihuahua: null
labrador: null
},
cats: {
persian: null
siamese: null
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment