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

The scrollTo() function does not function properly on iOS devices

When I try to scroll to my category list, the command works on Android but not on iOS. Here is a code example: @ViewChild(Content) content: Content; scrollTo() { this.content.scrollTo(0, 100, 200); } - <button ion-button (click)="scrollTo()"> ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

A guide to simulating components using providers in Angular 4 - Achieving successful unit testing

I am struggling with mocking a component that uses providers in Angular 4. Below is the code snippet I am working on: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; i ...

Tips for setting up chrome-app typings in Typescript 2

I am looking to eliminate the typings in our Typescript project. After successfully removing most typings dependencies with Typescript 2, I'm left with just one for chrome-app: https://github.com/uProxy/uproxy/compare/master...fortuna:master When usi ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

A guide to populating a Dropdown List in Angular2 with data from a JSON response

I am facing an issue where the data I receive from my web server is showing up as undefined when trying to bind it into my front-end application. The array seems to be populated with the correct number of objects, and the data is binding to the component b ...

What is the process of adding an m4v video to a create-next-app using typescript?

I encountered an issue with the following error: ./components/Hero.tsx:2:0 Module not found: Can't resolve '../media/HeroVideo1-Red-Compressed.m4v' 1 | import React, { useState } from 'react'; > 2 | import Video from '../ ...

The issue with Angular 2's router.navigate not functioning as expected within a nested JavaScript function

Consider the app module: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angul ...

What's the best way to show the calendar date in the mm-dd-yyyy format within an input search tag in Angular

I have implemented the <input class="input-group1 search" id="to" placeholder="dd-mm-yyyy" [(ngModel)]="toDate" value="" name="dp3" type="date"> in my code, which currently di ...

When the observable is subscribed to, the data is not immediately available

I am encountering an issue with syncing data from an observable in a service with a component that consumes the data. The data service makes a call to an api service upon creation to gather a list of devices from a server. It seems like this process is fun ...

Tips for including new items in an array within a subscribe valueChanges in Angular

What is the process for extracting values from a reactive form and storing them in an array when the form is valid? My application features dynamic forms with various fields that appear dynamically. retrieveFormValues(){ let valuesArray = []; this.fo ...

Limiting querySelector to a specific React component: a step-by-step guide

Is there a way to target a specific DOM element within a React component to change its color using the ComponentDidMount method? Parent component export class ListComponent extends Component<...> { render(): ReactNode { return ( ...

Pagination in Laravel using Angular 5

Currently experiencing pagination issues in an Angular5 and Laravel5 project. The JSON values are as follows: { "products": { "current_page": 1, "data": [ ... ], "first_page_url": "http://localhost:8000/api/ ...

Disarrayed generic parameters in TypeScript

The title of the question may not be perfect, but it's the best I could do. Imagine a scenario where there is a function that accepts a callback along with an optional array. The callback takes an index and another optional array as parameters, and t ...

Choose the default value of the select tag if hardcoded options are used with ngModel

When the value is set by using this.model.type = OPTION_NR1, Angular automatically sets the HTML attribute ng-reflect-model to 0. However, the desired value for this HTML attribute should be OPTION_NR1 in order to populate the drop-down with Option1 instea ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

What could be the reason for my Angular website displaying a directory instead of the expected content when deployed on I

My current challenge involves publishing an Angular application to a Windows server through IIS. Upon opening the site, instead of displaying the actual content, it shows a directory. However, when I manually click on index.html, the site appears as intend ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...