Javascript - Transforming tabular information into a hierarchical tree structure (JSON)

When extracting JSON data from a table, the format typically resembles the following simplified structure:

https://i.sstatic.net/eqfXM.png

The JSON format obtained might look like this:

const myObjOriginal = {
  "rows": [{
    "name": "row 1",
    "cells": [{
      "name": "level 1",
      "id": 1
    }, {
      "name": "first level 2",
      "id": 2
    }, {
      "name": "endpoint 1",
      "id": 4
    }]
  },
  {
    "name": "row 2",
    "cells": [{
      "name": "level 1",
      "id": 1
    },
    {
      "name": "first level 2",
      "id": 2
    },
    {
      "name": "endpoint 2",
      "id": 5
    }]
  },
  {
    "name": "row 3",
    "cells": [{
      "name": "level 1",
      "id": 1
    },
    {
      "name": "second level 2",
      "id": 3
    },
    {
      "name": "endpoint 3",
      "id": 6
    }]
  }]
};

The task at hand is to transform this structure into a tree layout instead of a tabular one, producing output similar to this:

const goalObject = [{
  "name": "level 1",
  "id": 2,
  "children": [{
    "name": "first level 2",
    "id": 2,
    "children": [{
      "name": "endpoint 1",
      "id": 4
    }, {
      "name": "endpoint 2",
      "id": 5
    }]
  }, {
    "name": "second level 2",
    "id": 3,
    "children": [{
      "name": "endpoint 3",
      "id": 6
    }]
  }]
}];

Various methods like map, reduce, filter, loops, and forEach have been attempted without success. It's clear that implementing a recursive function is necessary, but achieving this has proven challenging.

An attempt was made using the code snippet below, although it's recognized as incorrect:

function getChildrenOfCurrentItem(rowIndex = 0, cellIndex = 0) {
  let current = {};
  let myObj = {};

  for(let i = 0; i < myCopy.rows.length; i++){
    next = myCopy.rows[i].cells[cellIndex];
    const cells = myCopy.rows[i].cells;
    const isSame = compareObjects(current, next);

    if(!isSame){
      current = next;
      myObj.item = current;

      for(let j = 0; j < cells.length; j++){
        let cell = cells[j];
        console.log('cell', cell);
      }
    }

    console.log('myObj', myObj);

    if(cellIndex < max) {
        getChildrenOfCurrentItem(rowIndex, cellIndex);
    }
    rowIndex++;
  }
  return myObj;
}

Answer №1

If you're looking to group elements with the same id, one approach is to use an iterative method.

var data = { rows: [{ name: "row 1", cells: [{ name: "level 1", id: 1 }, { name: "first level 2", id: 2 }, { name: "endpoint 1", id: 4 }] }, { name: "row 2", cells: [{ name: "level 1", id: 1 }, { name: "first level 2", id: 2 }, { name: "endpoint 2", id: 5 }] }, { name: "row 3", cells: [{ name: "level 1", id: 1 }, { name: "second level 2", id: 3 }, { name: "endpoint 3", id: 6 }] }] },
    result = [];

data.rows.forEach(({ cells }) => {
    cells.reduce((level, { name, id }) => {
        var temp = (level.children = level.children || []).find(o => o.id === id);
        if (!temp) {
            temp = { name, id };
            level.children.push(temp);
        }
        return temp;
    }, { children: result });
});

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

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

Could someone clarify the specific workings of the Google V8 bytecode related to the creation of object literals

Check out this awesome piece of JavaScript code! const person = { name: 'John', age: 30 }; console.log(person); Here's the Google V8 byte code generated by using node js option --print-bytecode. [generated bytecode for function:] ...

What is the best way to transmit extra data when tunneling a TLS connection?

I have developed a basic HTTP proxy that utilizes the HTTP CONNECT method for HTTP tunneling. const http = require('http'); const https = require('https'); const pem = require('pem'); const net = require('net'); con ...

Passing the results of sequelize through express after the completion of a forEach iteration

In an express route, I am running a somewhat complex sequelize query that requires me to run a second query afterward to append necessary data to the result: //Get inboxes based on passed params router.get('/:data', function(req, res, next) { ...

Formulate a jQuery array consisting of droppable components

I have successfully implemented draggable li-elements and droppable boxes using jQuery UI. Here is my structure: A list of 3 different permission types <ul> <li data-action="create">Create</li> <li data-action="edit">Edi ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...

Is the text in bold format or not detectable in contenteditable mode?

I am currently working on developing a custom text editor using the built-in contenteditable feature in HTML. I am trying to figure out how to determine whether the selected text is bold or not within the editor. This is what my current setup looks like: ...

An efficient way to store a JavaScript-generated countdown timer in MySQL using PHP

Can anyone provide guidance on how to save a JavaScript-rendered countdown timer into a MySQL database using PHP? For example, I have a button that, when clicked, triggers the countdown timer to start. My issue lies in figuring out the best method to ensu ...

Unsure of the datatype for a particular field in a JSON object? No problem - here's how to

Working with a JSON response, I am using Jackson to parse it. However, the type of one field is unknown. For example: {"name" : "Catalina"} OR {"name" : {"First" : "Catalina", "Last" : "Kyle"}} How can I deserialize this object into a POJO? class Nam ...

Tips for sending a parameter to a URL from a controller using AngularJS

I am currently working on a feature where I need to combine adding and editing functionalities on one page. The items are listed in a table below, and when the edit button is clicked, I want to pass the ID of that specific item in the URL. This way, if the ...

Problem with Node JS controller when using async/await

While working on my Node API controller, I encountered an issue with my 'error-handler' middleware related to using an asynchronous function. TypeError: fn is not a function at eval (webpack:///./app/middleware/errorHandler.js?:16:21) T ...

Is it possible to pass an array to a class constructor in JavaScript using destructuring?

I am interested in developing a Statistics class that can handle 25 inputs (or possibly more or less) and perform calculations to find values such as mean, median, mode, range, variance, and standard deviation. Is it possible to achieve something like thi ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Navigating within a React application using React Router 2.6.0 by triggering a redirection within a click

Currently, I am experiencing an issue while utilizing react-router for constructing a login system with firebase and react. The desired functionality involves redirecting the user to the home page upon successful authentication of their username and passw ...

Transforming JSON Array into CSV Format

Having trouble converting a JSON array into a CSV file using jq. The JSON output from the curl command is as follows: { "requestID": "463aeb25-f4c3-40ba-a031-e62d698afc6e", "signature": { "id": "json&quo ...

Sorting through a Json array

I'm new to working with JSON and struggling to filter an array to retrieve all values (store) where id_estado=1. Any suggestions on how I should tackle this? JA1= [{"id_estado":"1","tienda":"Aurrera"},{"id_estado":"1","tienda":"Walt-Mart"},{"id_esta ...

Triggering the AJAX function in the main window

My HTML webpage has a hyperlink that, when clicked, opens the same page in another window with a hash value appended to the URL using window.open. For example, the URL could look like this: http://mywebsite.com#hash=value The webpage contains a JavaScript ...

Eliminate null values from a JSON dataset in Python

Whenever I fetch data from Firebase using the Rest API, the structure appears like this. { "Dataset1": [ null, { "Key1": 1, "Key2": 2 }, { "Key1": 3, "Key2": 4 ...

Adjusting hyperlinks placement based on window size changes using jQuery

On resizing the screen, I am moving the sub-nav links to the '#MoreList' It works well initially, but when the window is expanded again, the links remain in the #MoreList instead of going back to their original positions if there is enough space ...

Utilizing JSON Data in MVC View .cshtml: A Comprehensive Guide

I am seeking assistance with a challenge I am facing. I have a web service that returns JSON data in the following format: {"stations":[{"name":"aname","free":false},{"name":"anothername","free":true}]} This JSON consists of an array of objects, each con ...