Convert the Angular PrimeNG class into a TreeNode object to avoid the error of trying to access the map property of an

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...

Answer №1

I managed to solve my issue, which in hindsight was quite silly. I mistakenly attempted to iterate on a function that required continents when I was actually trying to convert countries. Fortunately, everything worked smoothly with other functions designed specifically for transforming countries:

private convertContinentsToTreeNodes(continents: Continent[]) {
    for (let cont of continents) {
        this.continentNodes.push(this.convertContinentToTreeNode(cont));
    }
}

private convertContinentToTreeNode(cont: Continent): TreeNode {
    let countryTreeNodes: TreeNode[] = [];

    if (cont.countries !== undefined) {
        for (let c of cont.countries) {
            countryTreeNodes.push(this.convertCountryToTreeNode(c));
        }
    }
    return {
        label: cont.name,
        data: cont,
        children: countryTreeNodes
    };
}

private convertCountryToTreeNode(country: Country): TreeNode {
    return {
        label: country.name,
        data: country
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to configuring a not null property in Typescript Sequelize:

Hello there! I am trying to figure out how to set a not null property using TypeScript Sequelize. I have tried using the @NotNull decorator, but unfortunately it does not seem to be working. The errors I am encountering are as follows: Validation error: W ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

Adjusting the height dynamically of the final div to accommodate various screen resolutions using Angular 8

I am currently developing an enterprise application with Angular, featuring a Sidebar on the left and content on the right. The content container includes text at the top and dynamic elements like tables that need to be displayed below it. To achieve this ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

The functionality for handling gestures on AgmMap appears to be non-functional

I am currently using the AGM Map feature available on and I need to disable the zooming functionality when scrolling. Despite setting gestureHandling = "'cooperative'", it does not seem to work. Are there any specific factors causing this issue? ...

Angular project set up with dynamic polyfill inclusion based on .browserslistrc configuration

In order to ensure that our software is compatible with older browser versions, we need to implement polyfills for Angular since it does not do this automatically. To achieve this, I am looking to add custom webpack configuration. Currently, I am working ...

What is the best way to retrieve the current height in VueJS using the Composition API?

I am utilizing a Ref to preserve the current height of the active element. My goal now is to transfer this height to the subsequent element that gets clicked on. <script lang="ts" setup> import { ref, reactive } from "vue"; defin ...

Typescript is struggling to locate a module that was specified in the "paths" configuration

Within my React project, I have set up a module alias in the webpack config. Now, I am looking to transition to Typescript. // I have tried to simplify the setup as much as possible Here is my tsconfig.json located in the root directory: { "compilerOp ...

Angular-Slickgrid: Some filters may not display on the header row

After thorough investigation and experimentation, I was able to identify both the issue and a suitable solution: The problem stemmed from our dataset's usage of numeric IDs (e.g. 1,2,3,...). Within the code, there was an error where the grid misinter ...

Trouble in paradise: Typescript version inconsistency within nx monorepo (NestJS + Angular)

Exploring the realms of Angular, NestJS, and Nx monorepos has been an exciting journey for me. Currently, I am delving into a detailed tutorial that guides through the setup process step by step. It all begins with setting up an nx project using nest: npx ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

What is the best way to send an email with a time-sensitive code (token) using Firebase?

Currently, I am developing an application that requires sending a verification code to users before they can proceed with certain actions. For instance, when users log in to the app, they need to enter their email, password (authenticated using Firebase au ...

Can browser-sync be used to update sass/css for angular 2 components through injection?

Currently, I am using browser-sync to dynamically inject and modify the CSS in my application's root stylesheets that are not directly managed by Angular. Surprisingly, this process does not require a reload. However, I have noticed that any changes ...

Instantiate a TypeScript object and establish its type by setting restrictions derived from an input object

I have been working on creating a function that takes an object A: { [key: string]: string | undefined } as its parameter. The goal is to generate a new object B with all properties from A, converting each string property to type number, and each string | ...

Navigating Unknown Properties in Angular: A Guide to Iterating Through Arrays

I'm having trouble coming up with a title for my question. I want to loop through an array of dynamic objects coming from a database, but I don't know the properties of the objects. Here's an example of the array object: [{ "id": 9, ...

Testing files outside of the project directory in Angular + Karma can present challenges in performing thorough analysis and evaluation

I have a file structure set up as follows: projects myproj - Angular App myproj-lib - Angular Library shared - shared code used in both the app and the library Both the App and Lib projects were created using Angular CLI (angular.json has not been mo ...

Currently, I am faced with a TS1109 error in my Angular project, where an expression is expected

While following the tutorial at https://developers.google.com/codelabs/building-a-web-app-with-angular-and-firebase#4, I encountered an error on line 11: todo: Task[] = [...]; The tutorial did not provide any solution for this error, and now I am stuck. i ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...