I'm struggling to create a tree structure from a flat array using two Mock data tables in JSON. The table should match the unique IDs to determine the hierarchy between them.
JSON with Groups DB array example:
{
"group": [
{
"groupName": "ROOT",
"id": 1
},
{
"groupName": "Family",
"id": 9
},
{
"groupName": "BestFriends!",
"id": 10
},
{
"groupName": "Cars",
"id": 4
},
{
"groupName": "funHouse",
"id": 3
}
]
};
JSON including Users array example:
{
"user": [
{
"username": "StrongGoose",
"password": "sdff12fdsa",
"age": 31,
"id": 2
},
{
"username": "John",
"password": "sdjd34fffdsa",
"age": 31,
"id": 3
},
{
"username": "Mary",
"password": "sdfffdsa",
"age": 31,
"id": 4
}
]
};
This is how the first data table looks and determines the hierarchy between groups:
{
"GroupsToGroups": [
{
"1":[9,10]
},
{
"10":[3]
}
]
};
The second one shows which user belongs to which group:
{
"GroupsToUsers": [
{
"11":[2]
},
{
"3":[3]
},
{
"4":[4]
},
{
"10":[2]
},
{
"3":[3]
}
]
};
The desired Hierarchy format written in JSON:
[
{
"type": "group",
"id": "1",
"name": "ROOT",
"items": [
{
"type": "group",
"id": "9",
"name": "Family",
"items": []
},
{
"type": "group",
"id": "10",
"name": "BestFriends!",
"items": [
{
"username": "StrongGoose",
"password": "sdff12fdsa",
"age": 31,
"id": 2
},
{
"type": "group",
"id": "3",
"name": "funHouse",
"items": [
{
"username": "John",
"password": "sdjd34fffdsa",
"age": 31,
"id": 3
},
{
"type": "group",
"id": "4",
"name": "Cars",
"items": [
{
"username": "Mary",
"password": "sdfffdsa",
"age": 31,
"id": 4
}
],
}
]
}
]
}
]
}
];
Edit: I have attempted to create a recursive function that finds the relevant related groups. It works but I am unsure of how to combine the users.
function checkChildren(group) {
const allChildren = insideGroups[group.id];
if (!allChildren) return group;
const childGroups = allChildren.map((findChildrenID) => {
const indexGroups = groups.findIndex((subGroup) => subGroup.id ===
findChildrenID);
return checkChildren(groups[indexGroups]);
});
return Object.assign({}, group, {groups: childGroups});
}