Last active
July 29, 2019 21:31
-
-
Save LFTroya/23be4d1847859f94f38738d7deeb8dff to your computer and use it in GitHub Desktop.
Snippet to build a nested tree
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
const arr = [ | |
{id: 1, title: 'hello', parent_id: 0}, | |
{id: 2, title: 'hello', parent_id: 0}, | |
{id: 3, title: 'hello', parent_id: 1}, | |
{id: 4, title: 'hello', parent_id: 3}, | |
{id: 5, title: 'hello', parent_id: 4}, | |
{id: 6, title: 'hello', parent_id: 4}, | |
{id: 7, title: 'hello', parent_id: 3}, | |
{id: 8, title: 'hello', parent_id: 2} | |
]; | |
function transformToTree(arr, parentKey = 'parent_id', idKey = 'id'){ | |
var nodes = {}; | |
return arr.filter(function(obj){ | |
var id = obj[idKey], | |
parentId = obj[parentKey]; | |
nodes[id] = Object.assign(obj, nodes[id], { children: [] }); | |
parentId && (nodes[parentId] = (nodes[parentId] || { children: [] }))["children"].push(obj); | |
return !parentId; | |
}); | |
} | |
console.log(JSON.stringify(transformToTree(arr))); | |
exports = {transformToTree}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment