Created
September 21, 2017 05:27
-
-
Save SakoMe/4aab46c331941f6a904d174668e1cb11 to your computer and use it in GitHub Desktop.
Taking an array of objects and representing as a tree using recursion
This file contains hidden or 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
// 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