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

JQuery fixed div bounces unpredictably when scrolling

Currently, I have a scenario on my webpage where there is a div called RightSide positioned on the far right side below another div named TopBanner. The TopBanner div remains fixed at the top of the screen even when the user scrolls down, which is exactly ...

Interactive pop-up text box for data cells in a table

I have implemented a textarea in the td cell of each row within column 3 to store description specific to that row. The goal is for the current description in the td's textarea to be copied over to the textarea located inside #div_toggle when the user ...

Unusual behavior exhibited by dynamic code in iframe

When trying to retrieve a dynamic height iframe, I implement the code below. In the <head> area <script language="javascript" type="text/javascript"> function adjustIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight ...

How to send the value of a JavaScript loop variable to PHP using AJAX

How can I send variables in a loop to a PHP file using AJAX? var lat; var lng; var array = [22.399602, 114.041176, 22.344043, 114.0168, 22.327529, 114.087181]; console.log(array); for (var i = 0; i < 6; i += 2) { lat = array[i]; console.log("l ...

Change UL to a JSON format

I am attempting to transform an entire unordered list (UL) and its child elements into a JSON object. Here is the approach we took: function extractData(element) { element.find('li').each(function () { data.push({ "name": $(this).fi ...

Switch images when hovering

I currently have two dropdown menus called NEW and SHOP. When I hover over the New Menu 1, it should display the corresponding image. Similarly, when hovering over New Menu 2, the related image should be shown in a div with the ".menu-viewer" class. Whil ...

Scrolling with Jquery window.scrollTo results in the page becoming unresponsive

I'm currently revamping a website that features a header with 100% screen height, but I need it to shrink down to 0px when a user starts scrolling. The issue I'm facing is that once the header shrinks to 0px, the page content ends up slightly abo ...

Unusual Behavior Uncovered in jQuery Selectors

Have you ever noticed a peculiar behavior of jQuery selectors? I recently discovered that when the page contains elements with non-unique IDs, jQuery returns different results for the same selectors: Here's an example of HTML code: <button id=&ap ...

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

What is the best approach to incorporate a stopwatch?

I'm exploring ways to track the time it takes for a user to click a button. While I have a working solution, I'm curious if there's a more efficient method available. Below is my current implementation: export class MainComponent implements ...

Please display the Bootstrap Modal first before continuing

Currently, I'm facing a challenge with my JS code as it seems to continue running before displaying my Bootstrap Modal. On this website, users are required to input information and upon pressing the Save button, a function called "passTimeToSpring()" ...

Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command: mocha ts/test --compilers ts:typescript-require Every time I make a change, it fails with an error message like this: error TS2307: Cannot find mo ...

if the input field is empty, eliminate the class

Within the code snippet, a function is present which performs the following actions. It searches for an email in the input field, then converts the email to an md5 hash, and finally generates a Gravatar URL that is inserted into a class using fadeIn(); ...

Need some assistance in finding a way to input multiple values from multiple buttons into a single input field in JavaScript

Hello, I am looking for a little help with reading multiple values using multiple buttons such as 1, 2, and 3, and displaying the output in the input like '123' instead of just one number at a time. Concatenate numbers with every click. <inpu ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Implementing TypeScript module resolution with Cucumber-js can be a bit tricky

Currently, I am in the process of creating a Proof of Concept for Cucumber-js using TypeScript. Everything is going smoothly except for one issue - I am facing difficulties when it comes to configuring the module resolution while utilizing tsconfig-paths. ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...