Last active
August 29, 2015 14:14
-
-
Save squallstar/19d08bd97d6cbeed405b to your computer and use it in GitHub Desktop.
Generate tree from flat pages
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
var pages = [ | |
{id: 1, parent: null, name: 'First'}, | |
{id: 2, parent: null, name: 'Second'}, | |
{id: 3, parent: 2, name: 'First child of second'}, | |
{id: 4, parent: 2, name: 'Second child of second'}, | |
{id: 5, parent: 2}, | |
{id: 6, parent: 4}, | |
{id: 7, parent: 4}, | |
{id: 8, parent: 6} | |
]; | |
console.log('here is the tree', generateTree(pages)); | |
function generateTree (pages) { | |
var map = {}, tree = []; | |
function addChildrenToPage (page) { | |
page.children = map[page.id] || []; | |
for (var i = 0; i < page.children.length; i++) { | |
addChildrenToPage(page.children[i], map); | |
} | |
}; | |
for (page of pages) { | |
if (!map[page.parent]) map[page.parent] = [page]; | |
else map[page.parent].push(page); | |
} | |
for (page of pages) { | |
if (page.parent == null) { | |
addChildrenToPage(page); | |
tree.push(page); | |
} | |
} | |
return tree; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment