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

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...

Resolving the issue of missing properties from type in a generic object - A step-by-step guide

Imagine a scenario where there is a library that exposes a `run` function as shown below: runner.ts export type Parameters = { [key: string]: string }; type runner = (args: Parameters) => void; export default function run(fn: runner, params: Parameter ...

Error found in Nuxt3 application when using locomotive scroll functionality

I'm working on a Nuxt3 project with Locomotive Scroll and GSAP (repository link: https://github.com/cyprianwaclaw/Skandynawia-Przystan). I'm facing an issue where, when I change the page from index to test and then revert back, the page doesn&apo ...

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

Tips for identifying unnecessary async statements in TypeScript code?

We have been encountering challenges in our app due to developers using async unnecessarily, particularly when the code is actually synchronous. This has led to issues like code running out of order and boolean statements returning unexpected results, espe ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Retrieve the file from the REST API without using the window.open method

I'm looking for a method to download files from an API without using window.open(). I want the download process to start immediately upon calling the API. Currently, I am downloading an .xls file generated by a REST API using window.open() API Endpo ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

What are the most optimal configurations for tsconfig.json in conjunction with node.js modules?

Presently, I have 2 files located in "./src": index.ts and setConfig.ts. Both of these files import 'fs' and 'path' as follows: const fs = require('fs'); const path = require('path'); ...and this is causing TypeScr ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

Sorting JSON arrays in Typescript or Angular with a custom order

Is there a way to properly sort a JSON array in Angular? Here is the array for reference: {"title":"DEASDFS","Id":11}, {"title":"AASDBSC","Id":2}, {"title":"JDADKL","Id":6}, {"title":"MDASDNO","Id":3}, {"title":"GHFASDI","Id":15}, {"title":"HASDFAI","Id": ...

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...

Attempting to invoke a TypeScript firebase function

I'm currently working on incorporating Firebase functions in my index.ts file: import * as functions from "firebase-functions"; export const helloWorld = functions.https.onRequest((request, response) => { functions.logger.info(" ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

Is it possible to invoke a function exclusively on the center item within an ngx-owl-carousel?

Is there a way to call a function only when an element is in the center of a slider? This is my HTML: <owl-carousel-o [options]="customOptions"> <ng-container *ngFor="let slide of slides"> <ng-template carous ...