Created
February 5, 2016 06:01
-
-
Save fercreek/a9d2f5151578ccb72747 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
let 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' } | |
] | |
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) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment