Skip to content

Instantly share code, notes, and snippets.

@casprwang
Created December 10, 2016 15:58
Show Gist options
  • Save casprwang/e9ec82a74dfc358d544f4ea3524a4664 to your computer and use it in GitHub Desktop.
Save casprwang/e9ec82a74dfc358d544f4ea3524a4664 to your computer and use it in GitHub Desktop.
let categories = [
{id: 'animals', 'parent': null},
{id: 'mammals', 'parent': 'animals'},
{id: 'dogs', 'parent': 'animals'},
{id: 'chihuahua', 'parent': 'dogs'},
{id: 'labrador', 'parent': 'dogs'},
{id: 'persian', 'parent': 'cats'},
]
let makeTree = (categories, parent) => {
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)
, null, 2)
)
/* output
{
"animals": {
"mammals": {},
"dogs": {
"chihuahua": {},
"labrador": {}
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment