Skip to content

Instantly share code, notes, and snippets.

@mikebarnhardt
Created January 16, 2018 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikebarnhardt/201e521c23677b7190bffa039cbd8b9e to your computer and use it in GitHub Desktop.
Save mikebarnhardt/201e521c23677b7190bffa039cbd8b9e to your computer and use it in GitHub Desktop.
Hierarchy tree from flat list
// Taken from https://stackoverflow.com/questions/22367711/construct-hierarchy-tree-from-flat-list-with-parent-field
function treeify(list, idAttr, parentAttr, childrenAttr) {
if (!idAttr) idAttr = 'id';
if (!parentAttr) parentAttr = 'parent';
if (!childrenAttr) childrenAttr = 'children';
var treeList = [];
var lookup = {};
list.forEach(function(obj) {
lookup[obj[idAttr]] = obj;
obj[childrenAttr] = [];
});
list.forEach(function(obj) {
if (obj[parentAttr] != null) {
lookup[obj[parentAttr]][childrenAttr].push(obj);
} else {
treeList.push(obj);
}
});
return treeList;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment