JSFiddle - React, Tailwind, and code Playground
JavaScript
var flatList = [
{
id: 1,
title: 'home'
},
{
id: 2,
title: 'about',
parent: 4
},
{
id: 3,
title: 'team'
},
{
id: 4,
title: 'company',
parent: 3
}
]
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 item as a root element.
rootElements.push(flatItem);
}
} else {
// No parent, add the item as a root element.
rootElements.push(flatItem);
}
});
return rootElements;
};