Navigating a vast JSON dataset containing identical key names: A step-by-step guide

I am faced with a massive json file that has the following format:

    name: 'xxx',
    worth: [123, 456, 789]
    children: [
       {name: 'xxx',
       worth: [987, 654, 321],
       children: [
          {name: 'xxx',
          worth: [213, 546, 879],
          children: []}
       },
       {name: 'xxx',
       worth: [987, 654, 321],
       children: [
          name: 'xxx',
          worth: [213, 546, 879],
          children: []
       }],
    ]

The depth of children can go up to 10 layers deep. I have developed an angular component that displays the name and worth while taking the children as an Input to recursively call itself with their respective names and worth. However, I encounter maximum stack size errors using this method.

I am struggling with how to design a function that can iterate through this json until the children array is empty, displaying the name and worth of each node along the way. While recursion seems like the logical choice for this task, I am having trouble implementing it...

Answer №1

If we assume that your root object represents a single child entity, the code structure would be as follows:

const child = {
  name: "xxx1",
  worth: [123, 456, 789],
  children: [
    {
      name: "xxx2",
      worth: [987, 654, 321],
      children: [
        {
          name: "xxx3",
          worth: [213, 546, 879],
          children: []
        }
      ]
    },
    {
      name: "xxx4",
      worth: [987, 654, 321],
      children: [
        {
          name: "xxx5",
          worth: [213, 546, 879],
          children: []
        }
      ]
    }
  ]
};

const sum = (arr) => arr.reduce((a, b) => a + b, 0);

function process_child(child, result) {
  const { name, worth, children } = child;
  result.push({ name, worth: sum(worth) });

  for (const c of children) {
    process_child(c, result);
  }

  return result;
}

const children = process_child(child, []);
console.table(children);

The process_child function is designed to handle a single child input along with an empty list of results. It iterates through all nested children to populate the result list. The final outcome is an array of objects structured as {name, worth}, which can be utilized according to your requirements.

This particular challenge does not pertain specifically to Angular. Your Angular component should primarily focus on consuming the data produced by this function in a passive manner.

For a live demonstration, you can view the working example on CodeSandbox. The output is shown on the page in JSON format.

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

Is there a way to send routerLink to an HTML element like <div [innerHTML]=""> without triggering the warning: "sanitizing HTML stripped some content"? Check out https://g.co/ng/security#xss for more information

Within the parent component, I am using the following construction: const link = `<a routerLink="${group.id}">${group.name}</a>`; // also tried using [routerLink] When attempting to work with it in a child component, I implement it l ...

Exploring the art of JSON interpretation within Highcharts

Below is an example snippet that utilizes static data: Highcharts.chart("container", { title: { text: "Highcharts pie chart" }, xAxis: { categories: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Ju ...

Exploring the nuances between Angular and Svelte in change detection mechanisms

In my daily work, I rely on Angular but also am taking the time to learn Svelte. As far as I know, neither Angular nor Svelte utilize a virtual dom and diffing process for change detection. Instead, they both have their own mechanisms for detecting chang ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

Angular2 Edit form does not have radio button selected according to the value

When editing a form, the radio button does not appear checked according to the value retrieved. I was able to retrieve the last name from the database, but when trying to bind the gender with the radio button, it does not show as checked. <div clas ...

I encountered difficulties in uploading my Angular application to GitHub Pages

I'm running into an issue when attempting to deploy my Angular application using GitHub pages. Here's the error message I encountered: about-me (master)*$ ngh An error occurred! Error: Unspecified error (run without silent option for detail) ...

The parameter type 'never[]' cannot be assigned to the type 'T | (() => T)' in the argument

Is it possible for the useFetch hook to allow any type of array to be used as the data type? hooks/useFetch.ts: const useFetch = <T extends any[]>(dataUrl: string) => { const [data, setData] = useState<T>([]); const [error, setError] = ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Decoding HttpResponse with Circe's Unmarshaller

I am attempting to request healthy services from consul. The response I received is as follows: HttpResponse(200 OK,List(X-Consul-Index: 3471242, X-Consul-Knownleader: true, X-Consul-Lastcontact: 0, Date: Fri, 02 Mar 2018 16:06:08 GMT),HttpEntity.Strict(a ...

Explaining the concept of SwitchMap in RxJS

Currently, I am utilizing Restangular within my Angular 5 project. Within the addErrorInterceptor section, there is a code snippet that invokes the refreshAccesstoken method and then retrieves the new access token in the switchMap segment. My approach invo ...

Exploring ways to loop through a JSON array and embed it into an HTML element

After the ajax request, the data returned is structured as follows: Data = [ ["18/02/2019", "A"], ["19/03/2019", "B"], ["21/05/2019", "C"], ] The ajax request was successful and the data is stored in a variable named Data within a function. ...

Error message pops up in WebStorm when attempting to access the map object in Angular

Within one of the services in my Angular application, I have utilized the map() function to retrieve data from the GitHub API. getUser(username: string) { // Regular Expression used for String Manipulation return this.http.get('https://api.github.com ...

When I attempt to read a JSON file using JSON SERDE, I am only fetching a single row

JSON Data: [{ "liked": "true", "user_id": "101", "video_end_type": "3", "minutes_played": "3", "video_id": "101", "geo_cd": "AP", "channel_id": "11", "creator_id": "101", "timestamp": "07/05/2019 01:36:35", "disliked": "true" }, { "lik ...

Using Python to Detect a Late-Rendered Image on a Webpage Using JSON

I'm currently in the process of reviewing a list of URLs to verify the presence of a specific image. So far, I have experimented with both selenium and beautiful soup but haven't been able to crack it. The appearance of the image is represented ...

What is the best way to retrieve a dynamic property from a JSON object in a Node.js environment?

While I know that this question may have been asked and answered multiple times before, I seem to be having trouble finding a solution that works for me. In my current project, I am using Node to make an API request and then returning the data to my Angul ...

What is the best way to integrate Bootstrap v4 into the most recent version of Angular?

npm install --save bootstrap I find the new version of Bootstrap to be less user-friendly compared to v4. Is there a way to install a specific older version of Bootstrap in an Angular project without getting the latest one? ...

Angular application using ngrx-store-localstorage does not retain data after a page refresh

Looking to incorporate ngrx into my authentication flow with the help of ngrx-store-localstorage for token persistence between browser sessions. After logging in, I can see the token value stored like this: {"token":{"token":"e5cb6515-149c-44df-88d1-4ff1 ...

Effectively Monitoring Angular Router Link Status

Is anyone else facing an issue with router link active not working correctly when navigating to a route with a different ID? The class is applied on the first navigation, but not on subsequent navigations. Any solutions? This is my HTML file: <div clas ...

Error: Unable to access the 'DASH' property as it is undefined

Within my current project, I aim to showcase data related to cryptocurrencies. After making an API call, I successfully obtained a response. The specifications of my environment are as follows: Node: 8.9.5, Express: 4.16.4, Angular CLI: 7.3.6, Typescript ...

The search parameter is not functioning properly when making the API request

I'm currently learning about json and APIs. The dataset I am experimenting with () allows for search functionality by adding ?search=search_term to the URL (e.g., ). However, when attempting to use a different json dataset (), it returns an error: { ...