I need assistance with creating a tree structure showing the hierarchy, I have a working code but my issue is with formatting the data to be displayed since the data is coming from 2 different arrays variables.
This how the output be should formatted.
- Terry Cats - Chief Creative Officer: Executive
- Nick Thompson - Head of Design: Operations
- Nick Jenson - Intern designer: Interns
- Nick Thompson - Head of Design: Operations
- Bruce Davids - Chief Strategy Officer: Executive
- David Smith - Head of Development: Operations
- John Jones - Head of Marketing: Operations
- Bill Bass - Chief Executive Officer: Executive
Here's my code.
const staffMembers = [
{
"_id" :0,
"name" : "David",
"surname" : "Smith",
"slug": "david-smith",
"category" : "operations",
"title": "Head of Development",
"reportsTo": "bruce-davids"
},
{
"_id" :1,
"name" : "John",
"surname" : "Jones",
"slug": "john-jones",
"category" : "operations",
"title": "Head of Marketing",
"reportsTo": "bruce-davids"
},
{
"_id" :3,
"name" : "Nick",
"surname" : "Thompson",
"slug": "nick-thompson",
"category" : "operations",
"title": "Head of Design",
"reportsTo": "terry-cats"
},
{
"_id" :4,
"name" : "Nick",
"surname" : "Jenson",
"slug": "nick-jenson",
"category" : "interns",
"title": "Intern designer",
"reportsTo": "nick-thompson"
},
{
"_id" :6,
"name" : "Terry",
"surname" : "Cats",
"slug": "terry-cats",
"category" : "c-suite",
"title": "Chief Creative Officer",
"reportsTo": ""
},
{
"_id" :7,
"name" : "Bruce",
"surname" : "Davids",
"slug": "bruce-davids",
"category" : "c-suite",
"title": "Chief Strategy Officer",
"reportsTo": ""
},
{
"_id" :8,
"name" : "Bill",
"surname" : "Bass",
"slug": "bill-bass",
"category" : "c-suite",
"title": "Chief Executive Officer",
"reportsTo": ""
}
]
const categories = [
{
"_id" :0,
"name" : "Executive",
"parent" : "",
"slug" : "c-suite"
},
{
"_id" :1,
"name" : "Operations",
"parent" : "c-suite",
"slug" : "operations"
},
{
"_id" :2,
"name" : "Interns",
"parent" : "operations",
"slug" : "interns"
},
];
const hierarchy = (data) => {
const tree = [];
const childOf = {};
let results = [];
let cat = "";
let childrens = [];
data.forEach((item,index) => {
const { slug, reportsTo, category } = item;
// console.log(category);
childOf[slug] = childOf[slug] || [];
item.children = childOf[slug];
reportsTo ? (childOf[reportsTo] = childOf[reportsTo] || []).push(item) : tree.push(item);
// if(category == categories.slug ){
cat = category;
const indexs = categories.findIndex(object => {
return object._id;
});
// }
});
for(let i = 0;i < tree.length;i++){
for(let j = 0;j < tree[i].children.length;j++){
childrens = (tree[i].children[j]);
}
results.push(tree[i].name + " " + tree[i].surname + " - " + tree[i].title +": "
+ cat + '*' + childrens.name + " " + childrens.surname + " - " + childrens.title + ": " + "cat"+cat);
}
return results;
};