Creating a hierarchical tree structure from tabular data with JavaScript ECMAScript 6

Seeking a JavaScript algorithm utilizing ECMAScript 6 features to efficiently convert JSON table data into a JSON tree structure. This approach should not employ the traditional recursive algorithm with ES5, but rather emphasize a functional programming methodology.

Original Table Data:

[
   {
      "Children":"4th Grand Father"
   },
   {
      "Name":"4th Grand Father",
      "Children":"3rd Grand Father"
   },
   {
      "Name":"3rd Grand Father",
      "Children":"2nd Grand Father"
   },
   {
      "Name":"2nd Grand Father",
      "Children":"Grand Father"
   },
   {
      "Name":"Grand Father",
      "Children":"Father"
   },
   {
      "Name":"Grand Father",
      "Children":"Uncle"
   },
   {
      "Name":"Uncle",
      "Children":"Cousin"
   },
   {
      "Name":"Father",
      "Children":"Brother"
   },
   {
      "Name":"Father",
      "Children":"Me"
   }
]

Converted Tree Data:

[
  {
    "Name": "4th Grand Father",
    "Children": [
      {
        "Name": "3rd Grand Father",
        "Children": [
          {
            "Name": "2nd Grand Father",
            "Children": [
              {
                "Name": "Grand Father",
                "Children": [
                  {
                    "Name": "Father",
                    "children": [
                      {
                        "Name": "Brother"
                      },
                      {
                        "Name": "Me"
                      }
                    ]
                  },
                  {
                    "Name": "Uncle",
                    "children": [
                      {
                        "Name": "Cousin"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

Answer №1

If you're looking for a solution using ES6 features like arrow functions, destructured argument assignment, and the Map, then this code snippet might be helpful:

const makeTree = (data) => {
    const hash = data.reduce( (acc, {Name, Children}) => 
        acc.set(Name, (acc.get(Name) || []).concat(Children)) 
    , new Map );

    const recurse = (Name) => hash.has(Name)
            ?   { Name, Children: hash.get(Name).map(recurse) }
            :   { Name };
    return recurse(undefined).Children;
}

// Sample data
const data = [
   {
      "Children":"4th Grand Father"
   },
   {
      "Name":"4th Grand Father",
      "Children":"3rd Grand Father"
   },
   // Additional sample data goes here...
];

const result = makeTree(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Explanation:

The hash variable is created using a Map, storing the data based on the key being the Name property. If a key already exists, the child is added to the array of children for that key. Recursion is used to build the tree structure starting from the top.

The end result is an object with a Children property that contains the desired hierarchical data.

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

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

Converting Avro to JSON array format in NiFi with nested arrays

Recently started exploring Nifi and wondering if it's possible to transform SQL results into JSON in a specific format. The current SQL result is shown below: member_id field2 total tax ship partnum price qty 874450963 24017 173.95 0 0 01593 ...

Clicking on Google Code Prettify does not trigger syntax highlighting

I utilize Google Code Prettify for syntax highlighting my code. Below is the HTML snippet I use: <head> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> </head> <body> ...

Package for running scripts in Node Package Manager

Currently, I am working on developing an npm package that will automatically insert a specific npm script into any package.json file that it is being used. Unfortunately, after going through the npm package.json/script documentation, I haven't been ab ...

Which is quicker: loading JSON via Ajax or loading the entire output through Ajax?

I'm interested in gathering different perspectives on this topic. Currently, I have Jquery initiating a function through ajax which loads data in two ways: The ajax script fetches JSON data from the server itself, then utilizes JavaScript to pars ...

The JQuery ajax post function is typically called towards the conclusion of a JavaScript script

I am struggling with validating whether a username is already taken. I have been attempting to determine if the username exists by utilizing the "post" method in jQuery. However, every time I execute this function, the script seems to skip to the end of th ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

Tips for resolving the 'Bad request error' when trying to create a new Cloudant document with an attachment

Currently, I am developing Python client examples to work with Cloudant NoSQL DB. Handling basic document creation is going smoothly. However, when attempting to upload a base64 encoded file as an attachment to the document, I’ve encountered a challengin ...

What is the best way to isolate particular components of an argument and store them in separate variables?

Currently, I am facing a challenge in extracting the name and id of an emoji from a discord argument using discord.js. The input provided to me is <:hack_wump:670702611627769876>, and my goal is to retrieve var id = '670702611627769876' along ...

ReactJs: Struggling to programmatically set focus on an element with React.createRef()

Looking to detect when a user clicks on an arrow using the keyboard? I stumbled upon the Arrow Keys React react module. To make it work, you need to call the focus method on a specific element. Manually clicking on an element does the trick: https://i.s ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

pressing the switch will adjust the size of the container

I am looking to implement a feature where clicking on an icon will resize a div to full screen in the browser. Below is the HTML code I have set up for this functionality, and I am open to suggestions on how to achieve this. <div> <a (click)= ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

Converting the HTTP response data from a Node server into a JSON file mapping

I am currently developing a solution where the web server, specifically using node with express, will utilize the request package to retrieve data from a web API. Upon receiving the data (which may include validation error status codes), it needs to be com ...

How can you retrieve the index of the outer repeater item within nested ng-repeaters in AngularJS?

If I have multiple ng-repeat loops nested within each other like in the following example: <div ng-repeat="outeritem in outerobject"> <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, $index)"></div> <d ...

Changing a single image within a v-for loop of images in Vue

I am currently working with an array in Vue where I am using v-for to create 3 columns of information. Each column includes an image, and I would like to be able to change only the specific image that is being hovered over without affecting any others. How ...

TabPanel with Grid component causes Error: The server-rendered UI does not match the initial UI, resulting in failed hydration

After completing all the necessary steps and transferring all the files from nextjs-with-typescript, everything seemed to be in order until I tried adding Grid inside the TabPanel in the code snippet below: import * as React from 'react'; Tabs fr ...

Unlocking keys of JavaScript class prior to class initialization

My constructor was becoming too large and difficult to maintain, so I came up with a solution to start refactoring it. However, even this new approach seemed bulky and prone to errors. constructor(data: Partial<BusinessConfiguration>) { if(!d ...

Tips for determining the size and identifier of a newly appended element in jQuery?

Struggling to create a select element with a width="347px" and id="select-box-1". I attempted to use .append("select"), but my search on .append() didn't yield the desired results. Unsuccessful Attempt: .append("< ...

In Vue, reactivity does not extend to nested child objects

I am dealing with JSON data structured like this- items: { id: 1, children: [{ id: 2, parentId: 1, children: [{ id: 3, parentId: 2 }] }] } level-1 children represent parent items that all possess a parent_id of 1 (the roo ...