Retrieving data from a nested JSON array using AngularJS

I am struggling to navigate the intricate nested tree view of child items within a JSON array. I have been grappling with this challenge for days, trying to figure out how to access multiple children from the complex JSON structure. Can someone provide guidance on how to access all children using Angular or JavaScript? Additionally, how can I identify which children belong to which parent? So far, I've only managed to retrieve the children of the first parents using the code snippet below:

assigning the JSON to value=datasource.data;

this.dataSource.data.forEach((item,i)=>{
            console.log(item.children);
            if(item.children){
              item.children.forEach((childItems,i)=>{
                console.log(childItems);
              })
            }


Here is the JSON:


TREE_DATA: FoodNode[] =
  
      [
      {
        name: 'Dashboard',
        id: "0",
        startButton: "enabled",
        stopButton: "enabled",
        type: "ec2",
        children: [
          {
            name: 'Backend-Server',
            id: "1",
            startButton: "enabled",
            stopButton: "enabled",
            type: "ec2",
            children: [
              {
                startButton: "disabled",
                stopButton: "enabled",
                type: "ec2",
                name: 'Backend-Server-1',
                id: "3"
              },
              {
                startButton: "enabled",
                stopButton: "disabled",
                type: "ec2",
                name: 'Backend-Server-2',
                id: "4"
              },
            ]
          },
          {
            startButton: "enabled",
            stopButton: "disabled",
            type: "rds",
            name: 'Frontend-Server',
            id: "5"
          },
          {
            startButton: "enabled",
            stopButton: "enabled",
            type: "ec2",
            name: 'Backup-Server',
            id: "6"
          },
        ]
      },
       {
        name: 'Admin',
        id: "7",
        startButton: "enabled",
        stopButton: "disabled",
        type: "ec2",
        children: [
          {
            name: 'Backend-Server',
            id: "8",
            startButton: "enabled",
            stopButton: "disabled",
            type: "ec2",
            children: [
              {
                startButton: "enabled",
                stopButton: "disabled",
                type: "ec2",
                name: 'Backend-Server-1',
                id: "9"
              },
              {
                startButton: "enabled",
                stopButton: "disabled",
                type: "ec2",
                name: 'Backend-Server-2',
                id: "10"
              },
            ]
          }, {
            startButton: "enabled",
            stopButton: "disabled",
            type: "ec2",
            name: 'Frontend-Server',
            id: "11",
            children: [
              {
                startButton: "enabled",
                stopButton: "disabled",
                type: "ec2",
                name: 'Frontend-Server-1',
                id: "12",
              },
              {
                startButton: "enabled",
                stopButton: "disabled",
                type: "ec2",
                name: 'Frontend-Server-3',
                id: "13"
              },
            ]
          },
        ]
      },
    ]

Answer №1

If you're dealing with a nested JSON, using a recursive function is essential. The solution below outlines how you can tackle this issue:

var childItems = [];

function getAllChildren(data) {
    data.forEach((item) => {
        if (item.children) {
            getAllChildren(item.children);
        } else {
            childItems.push(item);
        }
    });
}

getAllChildren(this.dataSource.data);
console.log(childItems);

Answer №2

In order to traverse a tree structure with children, you must implement recursion.

 const { data } = this.dataSource;
    var  childNodes=[];
    function traverseTree(data){  
        data.forEach((child)=>{
            (child.children)? traverseTree(child.children): childNodes.push(child);         
        });
    }
    
    traverseTree(data);
    console.warn(childNodes);

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

Arranging elements in ascending order in Java

I've been attempting to arrange an array in ascending order, following the instructions in example 104.5. Despite carefully reviewing my code multiple times, I'm unable to identify the mistake. Below is the code snippet from my sorting class: imp ...

The MongoDB operator "$in" does not recognize the type array that currently exists in the field

When attempting to execute an aggregate query in mongodb, I encountered an issue with the "$in" operator stating that the field passed is not recognized as an array. Here is the aggregate query being used: [ { '$match': { 'isVis ...

What is the best way to merge the results of several runs of an observable function

When working with Firestore, I need to retrieve multiple documents, each with a unique sourceAddressValue. This means for a list of N strings, I may need to fetch N documents. I attempted the following approach: getLocationAddresses(addresses: string[]) { ...

My Angular project is experiencing issues with Socket.IO functionality

After successfully using a post method in my endpoint, I encountered an error when integrating it with socket io. The error pertained to a connection error and method not being found. Any help or source code provided would be greatly ap ...

Modifying a 2-dimensional array with pointers

Every time I attempt to assign a value to an array using pointers, I encounter an error stating that float[int] is not a valid type. Here is the code I am using, which reads from a text file with the following content: 1 0.005 2 0.025 3 0.01 #include < ...

Encountered an issue when trying to deserialize the current JSON object while submitting relational data

I have encountered a problem while trying to add a worker to a job, specifically when dealing with the ModelState check. Here are the steps I've taken: Filling out the form Upon submitting the form, I checked the console and found: Name = "test", ...

Creating a Universal Resolver in Angular (2+) - A Step-by-Step Guide

I have a vision to develop an ultra-generic API Resolver for my application. The goal is to have all "GET" requests, with potential extension to other verbs in the future, utilize this resolver. I aim to pass the URL and request verb to the resolver, allow ...

Typescript's puzzling selection of the incorrect overload

I have a method structured as shown below: class Bar { public executeInWorker(cb: () => void): void; public executeInWorker(cb: () => Promise<void>): void | Promise<void>; public executeInWorker(cb: () => void | Promise< ...

Angular universal server-side rendering is functional on my local machine, however, it is encountering issues when

I've been delving into Angular Universal with nestjs. Everything seems to be running smoothly on my localhost at port 4000, but once I deploy the build on Netlify, the site functions properly except for Angular Universal. On my local machine, I use n ...

A guide to positioning the content of an Angular tag within a span element

Can someone help me figure out how to properly align the PO number and Vendor information on my page? from PO Number: 344 Vendor: yu PO Number: 3445 Vendor: yu PO Number: 344 Vendor: yu to PO Number: 344 Vendor: yu PO Number: 3445 Vendor: yu PO Num ...

How to import a node module into an Angular app through Angular CLI and load children in

My goal is to import a module from the node modules. This particular node module contains routes that I need to access. Here's what I want to achieve: I aim to configure my app.module to incorporate loadChildren from the module within my node module ...

"Encountering a Vue error while attempting to register the Can component globally with CASL +

I have successfully created a vue + typescript application using vue-cli. I followed the instructions from https://stalniy.github.io/casl/v4/en/package/casl-vue and added the following code: // main.ts import Vue from 'vue'; import App from &apo ...

What is the best way to create a new row within a Bootstrap table?

Struggling to format an array inside a table with the `.join()` method. The goal is to have each car on a separate row. Attempts using `.join("\r\n")` and `.join("<br />")` have been unsuccessful. What am I overlooking? ...

Utilizing React MUI Autocomplete to Save Selected Items

Exploring the realms of React and TypeScript, I find myself puzzled by a task at hand. It involves storing user-selected options from an Autocomplete component and subsequently sending these values to an external API. Is there a recommended approach for ac ...

Transform the array into JSON format in order to store it in the database

Hey, I have a unique array structure that looks like this: $data = Array( [0] => {"detail":"l,red","sku":"#123","price":"50","stok":""} [1] => {"detail":"l,black","sku":"#123","price":"50","stok":""} [2] => {"detail":"m,red","sku":"#123","price": ...

Incorporating a polling feature into an HTTP request within Angular 8

How can I implement a polling mechanism in order to fetch the status of a job (type Status) every minute for a service that requests this object with a specific JOB_ID as an argument? retrieveJobStatus$(JOB_ID): Observable<Status> { const url = ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

When attempting to utilize yarn link, I receive an error message indicating that the other folder is not recognized as a module

After successfully running "yarn link," I encountered an issue when attempting to use it in a different project. The error message displayed was ../../.tsx is not a module. What could be causing this problem? const App: React.FC = () => { const [op ...

Npm Installation Issue (Dependency Resolution Failure)

Whenever I attempt to execute npm install, I encounter the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

"Alert in Javascript executing prematurely prior to initiating the function for sending a get request

private validateURL(url: string) { let isValid = false; this.$http.get(url).then( (data) => { console.log('success'); isValid = true; } ).catch( (reason) => { console. ...