Skip to content

Instantly share code, notes, and snippets.

@LFTroya
Last active July 29, 2019 21:31
Show Gist options
  • Save LFTroya/23be4d1847859f94f38738d7deeb8dff to your computer and use it in GitHub Desktop.
Save LFTroya/23be4d1847859f94f38738d7deeb8dff to your computer and use it in GitHub Desktop.
Snippet to build a nested tree
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