Skip to content

Instantly share code, notes, and snippets.

@squallstar
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squallstar/19d08bd97d6cbeed405b to your computer and use it in GitHub Desktop.
Save squallstar/19d08bd97d6cbeed405b to your computer and use it in GitHub Desktop.
Generate tree from flat pages
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