Currently, I am working on a project that was created with JHipster and utilizes Angular 4.3. I want to incorporate the tree component from PrimeNG into this application.
My aim is to transform an array of objects into an array of TreeNodes so that it can be displayed as a tree structure.
This is what my typescript model looks like:
export class Continent implements BaseEntity {
constructor(
public id?: number,
public name?: string,
public countries?: Country[]
) { }
I came across this discussion which details how to convert interfaces (though in my case, it involves classes). Here are the functions I've implemented (and where I encountered an error):
private continentsToTreeNodes(continents: Continent[]) {
for (let cont of continents) {
this.continentsNodes.push(this.continentToTreeNode(cont));
}
}
private continentToTreeNode(cont: Continent): TreeNode {
return {
label: cont.name,
data: cont,
children: cont.countries.map(this.continentToTreeNode) // encountered error at this line: cannot read property map of undefined
};
}
These functions are triggered during the initialization of my component:
export class MyComponent implements OnInit {
continents: Continent[];
continentsNodes: TreeNode[] = [];
ngOnInit() {
this.loadAll();
}
loadAll() {
this.continentService.query().subscribe(
(res: ResponseWrapper) => {
this.continents = res.json;
this.continentsToTreeNodes(this.continents);
},
(res: ResponseWrapper) => this.onError(res.json)
);
}
}
Here's a snippet of my JSON data structure:
[{
"id": 1,
"name": "Africa",
"countries": [{
"id": 8,
"name": "Cameroon",
"continentId": 1
}, {
... // other countries
],{
// other continents
...
Can anyone help me understand why I'm encountering this error message related to my countries object?
EDIT : After adding logs to continentToTreeNode, I realized that the recursive function is causing the issue. The problem arises in the second loop, where the attribute cont.countries becomes undefined.
How is this happening and what steps can I take to resolve it? The JSON clearly includes all the countries for each continent...