Created
October 24, 2017 22:13
-
-
Save farskid/2c7227026ca8acc104ee6e850485a2ef to your computer and use it in GitHub Desktop.
Generate a tree from flatten array of data in Javascript
This file contains hidden or 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
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