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

The optional attribute feature in Angular directives

Looking for a solution: angular .module('test') .directive('multiButton', function () { return { restrict: 'E', replace: true, scope: { disabled: '@' }, template: ' ...

Issue with offset calculation in bootstrap table occurs when the bootstrap-table is closed and the window is resized

In a recent project, I utilized the bootstrap table. However, upon closing the bootstrap table with the following script: $(document).ready(function () { $(".removetable").click(function (e) { $(".table-aria").remove(); ...

Effectively importing a sizable dataset of Amazon product reviews into MongoDB with the help of Apache Spark

I'm currently tackling a project that involves loading a substantial Amazon product dataset (126 GB once uncompressed) into MongoDB using Apache Spark. The dataset is formatted as line-separated JSON. What strategies can I employ to optimize the data ...

Every time I hit the refresh button, I find myself forcefully logged out

After switching from using localStorage to cookies in my React JS web app, I am experiencing an issue where I get logged out whenever I refresh the page. Even though the cookies are still stored in the browser, the authentication process seems to be failin ...

Is there a way to retrieve the properties of another function within the same component?

I am trying to place NumberFormat inside OutlinedInput and I also need different properties for the format of NumberFormat. (There will be a select window that defines which format property to use). This is what I have: import OutlinedInput from "@ma ...

Postman Guide: Mastering the Evaluation of JSON Arrays

One of the features in Postman allows users to save a specific field from the response body as a variable and then utilize that variable in a subsequent call. For instance, after my initial call to the web service, the response body contains: [ { "id" ...

Adjust the start and end dates of the Bootstrap datepicker according to the chosen value

I am looking to dynamically set the startDate and endDate of a Bootstrap datepicker based on the value selected in an option form. For example, if I select "Boby" from the options, then the datepicker should be configured with startDate = 2016-10-04 and e ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

Struggles with fading in and out

I'm currently working on enhancing a pure CSS rollover with a smooth transition/fade effect, but I'm encountering some difficulties in achieving the desired outcome. The concept involves displaying a new div called "online-hover" when hovering o ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

What steps are needed to retrieve information from a website in an Android app following the input of personal information through the registration process?

Currently, I am in the process of developing an Android application that will collect various personal user details such as age, gender, income, etc., as well as their preferences for tax, scholarship, bank options, and more during the registration process ...

using jquery to fill in fields in a table form

I am currently working with a basic html table that initially has two rows, each containing 2 form fields. Users have the ability to add more rows to the table by following this process: $('a#addRow').click(function() { $('#jTable tr:la ...

Integrate CSS and JavaScript files into Node Express

I am facing an issue including my CSS file and JavaScript file in a node-express application, as I keep getting a 404 not found error. Here is the code snippet that I am using: 1. In server.js var http = require('http'); var app = require(' ...

Deleting an entry from a JSON file by comparing keys within the same array using the jq tool

I am working with a JSON file containing quiz questions. The format of the questions is as follows: { "ques": "What is the meaning of life?", "ans": "42", "Option1": "123", "Option2": "456", "Option3": "789", "Option4": "42" } { "ques": "Wha ...

Converting an image to base64 format for storing in localStorage using Javascript

Currently, I am working on code that sets the background-image of a link. This is what I have so far: $("a.link").css("background-image", "url('images/icon.png')"); However, I want to enhance it by storing the image in localStorage: if (!local ...

Tips for displaying a setCustomValidity message or tooltip without needing to submit the event

Currently, I am utilizing basic form validation to ensure that the email entered is in the correct format. Once validated, the data is sent via Ajax for further processing. During this process, I also check if the email address is already in use and whethe ...

Using Axios in Vuejs to prompt a file download dialog

I am currently working on figuring out how to trigger a file download dialog box after receiving an Ajax request from the Flask server using Axios. Here is my current client-side code snippet: <script> export default { ... exportCSV: function() { ...

Interop-require-default is nowhere to be found in the babel-runtime

I'm really stuck on how to resolve this error. I've tried searching online and followed the suggestions given by others. I even went as far as deleting 'node_modules' and reinstalling, but nothing seems to be working. The specific erro ...

Hide the scrollbars on the sidebar

I'm attempting to recreate a sleek scrollbar that caught my eye on the website . To achieve this, I need to have a screen larger than 955px in order to display the sidebar. However, when my sidebar overflows in the y direction, it causes an additional ...

Creating an embedded link to a website that adjusts to different screen sizes while also dynamically changing

I've been developing a personalized site builder that includes an iframe for previewing responsive websites. In order to make the site 'zoomed out' and not appear in mobile size, I'm utilizing CSS scale and transform origin as shown bel ...