Navigating through a node tree and making changes to its configuration and content

Here's the input I have. Some nodes have downlines with multiple other nodes nested inside.

data = [
  {
    "user_id": "1",
    "username": "johndoe001",
    "amount": "0.00",
    "downlines": [
      {
        "user_id": "2",
        "username": "j001-01",
        "amount": "1.00",
        "downlines": []...

How can I convert it to the output structure below?

[
    {
      "key": "1",
      "label": "johndoe001 (0.00)",
      "nodes": [
        {
          "key": "2",
          "label": "j001-01 (1.00)",
          "nodes": []...

I've managed to partially convert it using string replacements, but I'm struggling to update the label value by combining username and amount. Additionally, removing unnecessary keys like amount is posing a challenge.

let stringJson = JSON.stringify(data);
stringJson = stringJson.replace(/downlines/g, 'nodes');
stringJson = stringJson.replace(/username/g, 'label');
stringJson = stringJson.replace(/user_id/g, 'key');
let tmpTree = JSON.parse(stringJson);

Answer №1

Using a recursive function simplifies the process:

const data = [
  {
    "user_id": "1",
    "username": "johndoe001",
    "amount": "0.00",
    "downlines": [
      {
        "user_id": "2",
        "username": "j001-01",
        "amount": "1.00",
        "downlines": []
      },
    ]
  },
];

function rename(downlines) {
    return downlines.map(({ user_id, username, amount, downlines }) => ({
        key: user_id, // changing user_id to key
        label: `${username} (${amount})`, // adjusting label format
        nodes: rename(downlines), // recursively renaming other elements
    }));
}

console.log(rename(data));

If you find the ({ ... }) => syntax confusing, refer to destructuring on MDN.

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

Injecting dynamic templates in Angular 7

Let me simplify my issue: I am currently using NgxDatatable to display a CRUD table. I have a base component named CrudComponent, which manages all CRUD operations. This component was designed to be extended for all basic entities. The challenge I am en ...

Attempting to use a string as an index for the type `{ firstName: { inputWarning: string; inputRegex: RegExp; }` is not allowed

const checkRegexSignUp = { firstName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, lastName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, } const change = (e: ChangeEvent<HT ...

Event triggered by an Angular counter

Typescript: countdown; counter = 10; tick = 1000; this.countdown = Observable.timer(0, this.tick) .take(this.counter) .map(() => --this.counter) Also in HTML: <div> <h1>Time Remaining</h1> <h2>{{countdow ...

Encountering an error in Angular 2: "date.getMonth is not a function

I am currently utilizing the Angular-2-datepicker in my project. Everything seems to be functioning properly, but whenever I attempt to set the [(date)] attribute, an error is thrown. An error stating that date.getMonth is not a function keeps popping u ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

Encountered compilation errors while trying to compile the entry-point @ng-bootstrap/ng-bootstrap with `es2015` as esm2015. Compilation was unsuccessful

Seeking assistance in resolving the errors provided below. I am currently in the process of upgrading my angular project from version 8 to 12. Initially, I attempted to upgrade progressively from version to version, starting with "7 to 8, 8 to 9". However ...

Matching multiline input with RegExp and grouping matches from consecutive lines

Imagine having a text file with the following content: AAAA k1="123" k2="456" several lines of other stuff AAAA k1="789" k2="101" AAAA k1="121" k2="141" The objective is to extract the values of k1 and k2 while keeping them grouped together. For instance ...

Angular - Using the 'name' attribute with the 'mat-select' element

Currently, I am working on an Angular form that involves the dynamic nature of the userEntitiesRoles array. To ensure smooth functionality, each mat-select tag within the ngFor loop requires a unique name attribute. In order to achieve this, I attempted to ...

How can one access a dynamically generated element in Angular without using querySelector?

Currently in the process of developing my custom toastr service, as shown in the GIF below My Objective: https://stackblitz.com/edit/angular-ivy-tgm4st?file=src/app/app.component.ts But without using queryselector. It's recommended to avoid querysele ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

Terser is causing ng build --prod to fail

When I run ng build --prod on my Angular 7 application (which includes a C# app on the BE), I encounter the following error: ERROR in scripts.db02b1660e4ae815041b.js from Terser Unexpected token: keyword (var) [scripts.db02b1660e4ae815041b.js:5,8] It see ...

Having difficulty updating the value of a FieldArray with setFieldValue in Formik

Thank you for taking the time to read this. I am currently working on creating a form using Formik that involves nesting a FieldArray within another FieldArray. Oddly enough, setFieldValue seems to be functioning correctly as I can log the correct values ...

ExitDecorator in TypeScript

Introduction: In my current setup, I have an object called `Item` that consists of an array of `Group(s)`, with each group containing an array of `User(s)`. The `Item` object exposes various APIs such as `addUser`, `removeUser`, `addGroup`, `removeGroup`, ...

Error: An unexpected character (.) was encountered | Building with npm has failed

When executing "npm run build", I encounter an error with the unexpected token (.) related to object values. Can someone assist me in resolving this issue? I am using tsc build for a react npm library. It seems like there might be a configuration problem ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

A guide on streamlining the process of generating "this." variables within Angular

When it comes to working with Javascript, particularly Angular, I find myself using the this. syntax quite often. I'm curious to know if it's possible to concatenate variables in order to create a this. variable. For instance, is this achievab ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...