Skip to content

Instantly share code, notes, and snippets.

@farskid
Created October 24, 2017 22:13
Show Gist options
  • Save farskid/2c7227026ca8acc104ee6e850485a2ef to your computer and use it in GitHub Desktop.
Save farskid/2c7227026ca8acc104ee6e850485a2ef to your computer and use it in GitHub Desktop.
Generate a tree from flatten array of data in Javascript
function generateTree(list, id = 'slug', parentId = 'parent_slug', childrenId = 'children') {
var tree = [];
var lookup = {};
list.forEach(function(item) {
lookup[item[id]] = item;
item[childrenId] = [];
});
list.forEach(function(item) {
if (item[parentId] != null) {
lookup[item[parentId]][childrenId].push(item);
}
else {
tree.push(item);
}
});
return tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment