Discovering a specific node within a tree structure in an Angular component

I have a tree object with nested nodes and IDs

var data = [
{
 id: 'topNode',
 parameter: 'parameter',
 children: [
   {
       id: 'node1',
       parameter: 'parameter',
       children: [
       {
           id: 'randomNode_1',
           parameter: 'parameter'
       }],
   {   
       id: 'node2',
       parameter: 'parameter'
       children: [
           {
               id: 'randomNode_2',
               parameter: 'parameter'

           },
           {
               id: 'randomNode_3',
               parameter: 'parameter'

           }
       ]
   }
  ]
 }];

I am trying to search the tree for a specific node and return it

This is the method I wrote :

    findNodeById(idToFind: string, rootNode: TreeNode): TreeNode {
        if (rootNode.getId() === idToFind) {
               return rootNode;
        } else {
              for (const child of rootNode.getChildren()) {
                   this.findNodeById(idToFind, child);
              }
        }
   }

I call this method:

const foundNode: TreeNode = 
     this.findNodeById(event.currentTarget.id, this.treeRoot )

Unfortunately, the findNodeById method always returns undefined

Even though I place breakpoints at 'return rootNode;'

I'm stuck at this point and the node being returned is correct

UPDATE : I performed further debugging

  • If I add a return statement within the loop
      for (const child of rootNode.getChildren()) {
                  return this.findNodeById(idToFind, child);
              }

The method only explores the first branch (node1) to the end, and does not move on to the second one (node2)

  • If I remove the return statement in the loop
      for (const child of rootNode.getChildren()) {
                  this.findNodeById(idToFind, child);
              }

Once the node is found, the loop continues instead of stopping

Answer №1

Ensure to place the return statement before making a recursive call in the for of block:

findProposedValueById(idToFind: string, rootNode: TreeNode): TreeNode {
        if (rootNode.getId() === idToFind) {
               return rootNode;
        } else {
              for (const child of rootNode.getChildren()) {
                   return this.findProposedValueById(idToFind, child);
              }
        }
   }

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

Enhanced HTML support for * syntax in IntelliJ Angular 2

It appears that IntelliJ 2017.1 does not fully support the * syntax for HTML files with Angular 2. The autocompletion only suggests the template syntax without the star. https://i.stack.imgur.com/k6SuD.png https://i.stack.imgur.com/QfNPH.png Moreover, w ...

Error involving key mismatch between TypeScript inherited interface and literal string type

There are 3 interfaces (A, B, and C) that all extend from a shared interface (Common). Additionally, there is a container type which holds arrays of these 3 interfaces (Container). The goal is to select one of the arrays and extract a common property from ...

Transferring AgGrid context in a functional React component

I have been working on a component that utilizes AgGrid to display a table, with the data sourced from a Redux selector. My goal is to include a button within a cell in the table that triggers an action based on the specific row's data. However, I a ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

What is the best way to delay Angular for 5 seconds before initiating a page transition?

Just a quick inquiry - is there a way to have Angular wait for 5 seconds before redirecting to a different page? I attempted to implement this functionality within my function, but it doesn't appear to be functioning as expected: setTimeout(() => ...

What is the process for updating the background color of the header in ngx datatable?

I am looking to change the background color of the table header to blue. This is the HTML code I have: <ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHe ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

A guide to seamlessly uploading files to s3 using nextjs, node, and typescript

I've been struggling to successfully upload a basic image to s3 using ts/nextjs/node. Despite having all the necessary credentials and code in place, I'm still unable to get it working. Can someone please provide clear instructions on how to achi ...

React Material Select: The error is caused by the property 'renderValue' with an expected type, as declared within the 'IntrinsicAttributes & SelectProps' type

Encountering an error with React Material Select, specifically on the Render Value function. How can I resolve this issue while using TypeScript? What should be added to the renderValue line? Error: Type '(selected: Array<number>) => string& ...

Combining two arrays to create a unified column using Angular

Below is the structure of my JSON object: { "name": "Beans", "location": ["AT", "BB", "ZZ"], "container": ["Cont1", "Cont2", "Cont3"] } I would like to kno ...

Error: command not recognized

Whenever I attempt to execute ng build in my project directory, I encounter the following error message: bash: ng: command not found I'm puzzled as to what the issue might be. Could it be related to administrator privileges, my path configuration, ...

Storing data received from httpClient.get and utilizing it in the future after reading

Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends. import ...

Upon successfully maneuvering vendors who fail to load the NEXT.JS Link

Here is an image that is not displaying properly. The navbar's responsiveness seems to be causing the issue. return ( <Link key={index} href={'/'+item.id} > <li className="nav-item dropdown position-stati ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Leveraging property values in Angular 2 to dynamically generate HTML elements as tag names

Is it feasible to use a property as an HTML tag name? For instance, something along the lines of: <{{property.name}}>Hello world</{{property.name}}> ...

Resizing inputs in Ionic 2 alert boxes

Hello all! I am currently working with the Ionic 2 framework and could use some assistance. I am attempting to make alert inputs that are multi-line or use textareas instead of single line inputs. Any guidance on how to achieve this would be greatly appr ...

Leverage angular to dynamically update excel sheet with parsed data

Question: I am currently trying to pull data from a website using Angular and I would like to export this data into an Excel file. Additionally, I want the ability to update this file with more data in the future. Is there a library that can help achieve ...

Showing a solo item from an array in HTML using Angular

How can I display the account name instead of the accountId property value from my list of transaction items? I have a list of transactionitems with an accountId property, and all accounts are loaded in the accounts$ array. However, I am having trouble us ...

Creating Complex Dynamic Tables in Angular

In my current project, we are faced with the challenge of displaying complex tables similar to the ones shown in this article: (or view image). The cells within these tables are highly dynamic, pulling all their information from an API. We have approxima ...