JSFiddle - React, Tailwind, and code Playground
JavaScript
var flatList = [
{
id:1,
name: 'name1',
parent: 0
},
{
id:2,
name: 'name2',
parent: 1
},
{
id:3,
name: 'name3',
parent: 2
},
{
id:4,
name: 'name4',
parent: 1
},
{
id:5,
name: 'name5',
parent: 1
},
{
id:6,
name: 'name6',
parent: 5
}
];
var fromThisList = flatList;
var whereElementsIdIsInThisField = 'id';
var andTheReferenceToAParentIsInThisField = 'parent';
var andSaveTheChildrenInThisField = 'children';
var tree = buildTree(fromThisList, whereElementsIdIsInThisField, andTheReferenceToAParentIsInThisField, andSaveTheChildrenInThisField);
console.log(tree);
// Originally from: http://stackoverflow.com/questions/22367711/construct-hierarchy-tree-from-flat-list-with-parent-field/22367819#22367819
function buildTree(flatList, idFieldName, parentKeyFieldName, fieldNameForChildren) {
var rootElements = [];
var lookup = {};
// Take the flat list and transform it into a dictionary of key/values.
// This will allow us to quickly get the reference of an object like a lookup table.
flatList.forEach(function (flatItem) {
var itemId = flatItem[idFieldName];
lookup[itemId] = flatItem;
flatItem[fieldNameForChildren] = [];
});
// Iterate through the items and set the parent reference (if any).
// If this is a root level item (no parent), add it to the array of root elements (= the tree).
flatList.forEach(function (flatItem) {
var parentKey = flatItem[parentKeyFieldName];
if (parentKey != null) {
// Item is linked to a parent, retrieve the parent.
var parentObject = lookup[flatItem[parentKeyFieldName]];
if(parentObject){
// Parent found, add the item as a child.
parentObject[fieldNameForChildren].push(flatItem);
}else{
// No parent found, add the...