Created
January 16, 2018 14:08
-
-
Save mikebarnhardt/201e521c23677b7190bffa039cbd8b9e to your computer and use it in GitHub Desktop.
Hierarchy tree from flat list
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
// 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