Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format?

Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure?

Current data format

{
  "content": [
    {
      "dimension": "2019-12-13",
      "subList": [
        {
          "dimension": "2019-12-13",
          "subList": [
            {
              "dimension": "2019-12-13",
              "subList": []
            }
          ]
        }
      ]
    },
    {
      "dimension": "2019-12-13",
      "subList": [
        {
          "dimension": "2019-12-13",
          "subList": [
            {
              "dimension": "2019-12-13",
              "subList": []
            }
          ]
        }
      ]
    }
  ]
}

The expected result should look like this:

{
  "content": [
    {
      "data": {
        "dimension": "2019-12-13"
      },
      "children": [
        {
          "data": {
            "dimension": "2019-12-13"
          },
          "children": [
            {
              "data": {
                "dimension": "2019-12-13"
              },
              "children": []
            }
          ]
        }
      ]
    }
   ]
}

Answer №1

When working with a tree-like data structure, it is best to use a recursive function for the task.

Let's define the types we are working with more formally:

type NodeA = { // current node structure
  name: string
  children: NodeA[]
}

type NodeB = { // desired node structure
  info: {
    name: string
  }
  descendants: NodeB[]
}

The recursive function to transform nodes may resemble this:

const convertNode = (node: NodeA): NodeB => {
  return {
    info: {
      name: node.name
    },
    descendants: node.children.map(convertNode)
  }
}

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

Leveraging Javascript to generate universal HTML content for various Javascript files

Present Situation: I have a timesheet feature that enables users to input their leave, TOIL, and sick days along with the respective hours. Additionally, there is a table that dynamically adds a new row every time the plus button is clicked using the foll ...

Locate numbers 2, 3, 6, 7, and 10, and continue in numerical order, within the

Having trouble with this one. Does anyone know how to display the items like this: 2, 3, 6, 7, 10 and so on... Is there a jQuery or CSS hack that can achieve this? I'm stuck trying to figure it out .container { display: flex; flex-flow: row wra ...

What is the best way to reach the end of a countdown and hit 0

Is there a way to complete the countdown to 0 second? Once the countdown is finished, it will display 00days00hours00minutes01seconds I would like it to show 0 seconds like this 00days00hours00minutes00seconds. Is there a method to achieve this? Explore ...

Utilizing a jQuery variable within an .html() method

Can a Jquery if statement be used to display different content inside a div based on a variable? For example, if the variable is set to "cats", the displayed content might say "I like cats", and if it changes to "dogs", it would read "I like dogs". Is this ...

Use jQuery to set different background images for multiple divs at random time intervals

I am facing a challenge with displaying multiple divs next to each other on my website, each with a unique background image. I have written a script that randomly changes the background images at different time intervals, but currently all the images chang ...

A common method for incorporating personalized react-scripts into create-react-app

After creating a project using create-react-app in TypeScript, I am looking to integrate custom react-scripts without ejecting. What is the most effective approach to achieve this? ...

Step-by-step guide to minify Typescript files with Webpack

I am facing an issue in my webpack configuration while trying to minify the output bundle when working with TypeScript. Currently, only one file has been migrated to TypeScript in my project and it works fine with babel-node and the dev bundle without Ugli ...

The technique for concealing particular div elements is contingent upon the specific values within an array

My TypeScript code is returning an array in this format: allFlowerTypes (3) ['Rose', 'Bluebell' , 'Daisy'] I want to dynamically show or hide the following HTML content based on the array values above: <ul> <li> ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

What is the reason that (click) does not send my data within <button>, while (change) within <input> does in Angular and HTML?

I am facing an issue while trying to send data to my Glassfish RESTful server. The method is activated successfully when I use (change) inside the input tag, but it doesn't work when I try using (click) or (change) to activate the method. I attempted ...

Issue with jquery .val() function not functioning as expected

I am experimenting with the jQuery .val(value) function to set the value of an attribute using the code snippet below. <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">< ...

Sending JavaScript functions to PHP files via Ajax

My Current Project: I am currently developing a script that provides users with choices and generates new options based on their selections. To achieve this, I have created two scripts - one for the HTML structure of my page and another for fetching serve ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...

Using TypeScript: Functions incorporating properties

Recently, I made an interesting discovery in JavaScript: function foo() { console.log("FOO"); } foo.bar = "FOOBAR"; foo(); // logs "FOO" console.log(foo.bar); // "FOOBAR" This got me thinking: How would I repres ...

Managing JavaScript events in the console

Running a server for a video game in node.js where the console communicates with clients via websockets. I have a function to spawn enemies from a MySQL database, but I am encountering an error that seems to be related to a jQuery script... I want the scr ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

Is there a way to incorporate jQuery validation similar to MVC data annotation?

In my MVC project, I have a master/details view page. The Details section is actually a partial view containing input fields and a save button displayed below. <button type="button" id="btnAddDetails" class="btn btn-primary">Add Details <span cl ...

How can I display Bootstrap 4v6 Modal automatically when the page loads?

I have been attempting to create a subscription pop up modal box using the latest Bootstrap 4 framework. My goal is to have the subscription box appear automatically when the page loads, without requiring clients to click a button. Despite following variou ...

Enhance your TypeScript React development with NeoVim

As a newcomer to vim, I decided to test my configuration with react and typescript. To do this, I created a simple demo app using the command npx create-react-app demo --template typescript. Next, I opened the directory in neovim by running nvim .. However ...