I am trying to build a object that represents a large community and all of its subcommunities. It essentially is a hiarchy of main community with multiple nested communities that have one or more nested communities themselves.
There is a factor of recursion to take into consideration, this is how the data structure should look like at the end:
{
id: "1",
name: "Car Club",
communities: [
{
id: "11",
name: "Euro Group",
communities: [
{
id: "111",
name: "Ferrari Club"
}, {
id: "112",
name: "Audi Club"
}
]
},
{
id: "12",
name: "Asian Fan Club",
communities: [
{
id: "121",
name: "Japanese Club",
communities: [
{
id: "1211",
name: "Toyota Group"
}, {
id: "1212",
name: "Suzuki Group"
}
]
}, {
id: "122",
name: "Great Wall Group"
}
]
}
]
}
This is as far as i got before my brain blew up.
export class Community {
id: string;
name: string;
communities: Community[]; // think of it sub communities
}
getCommunityById(id: string){
this.communityService.getById(id) // this calls the remote server for data
.subscribe((res: any) => {
var community = new Community();
community.id = res.id
community.name = res.name;
if (community.communities?.length) {
community.communities = [];
community.communities.forEach((e: any) => {
var community = getCommunityById(e.id);
community.communities.push(community);
});
}
});
}
I know the above is incorrect, but here we are.
Appreciate helping me untangle the spaghetti code above.