Last active
August 20, 2018 06:20
-
-
Save jossmac/6e1a97df43f31aa433951e0f749d0548 to your computer and use it in GitHub Desktop.
Experiment: Recursion
This file contains 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
const CATEGORIES = [ | |
{ id: 'animals', parent: null }, | |
{ id: 'mammals', parent: 'animals' }, | |
{ id: 'cats', parent: 'mammals' }, | |
{ id: 'dogs', parent: 'mammals' }, | |
{ id: 'labrador', parent: 'dogs' }, | |
{ id: 'cocker spaniel', parent: 'dogs' }, | |
{ id: 'rag doll', parent: 'cats' }, | |
{ id: 'burmese', parent: 'cats' }, | |
]; | |
let i = 0; | |
const makeTree = (items, parent) => { | |
let node = {}; | |
items | |
.filter(c => c.parent === parent) | |
.forEach(c => { | |
console.log(i++, c.id, parent); | |
node[c.id] = makeTree(items, c.id); | |
}); | |
return node; | |
}; | |
console.log(JSON.stringify( | |
makeTree(CATEGORIES, null), null, 2 | |
)); | |
{ | |
"animals": { | |
"mammals": { | |
"cats": { | |
"rag doll": {}, | |
"burmese": {} | |
}, | |
"dogs": { | |
"labrador": {}, | |
"cocker spaniel": {} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment