Convert an object into a tree structure for TreeTable, grouping by two levels in Typescript or JavaScript

I am currently working on transforming a list into a tree structure suitable for a PrimeNG TreeTable.

[{pk:"1", corpID:"1234", date: "31/03/21", rela:"4325", price:"20.00"},
{pk:"2", corpID:"1234", date: "21/03/21", rela:"4425", price:"50.00"} ,
{pk:"3", corpID:"3456", date: "03/03/21", rela:"6327", price:"80.00"} ,
{pk:"4", corpID:"4567", date: "05/03/21", rela:"7328", price:"40.00"}]

My objective is to group the data first by corpId, and then by rela. The PrimeNG TreeTable requires a specific structure where data represents the values displayed in each row, and children contain the data within the expanded row. For reference, you can check out this link: https://www.primefaces.org/primeng/showcase/#/treetable The desired structure should look like this:

{ data : [
    
        { 
            data: {
                corpID : "1234"
                },
                children: [
                   {
                   data:{ 
                     RELA: "4325"
                },
                children: [
                        {
                        data : { pk:"1",
                                 corpID:"1234",
                                 date: "31/03/21", 
                                 rela:"4325",
                                 price:"20.00"},
                        }]
                 },
                data:{ 
                   RELA: "4425"
                },
                children: [
                        {
                               { pk:"2", 
                                 corpID:"2345",
                                 date: "21/03/21",
                                 rela:"4425", 
                                 price:"50.00"
                         }
                       ]
...

I have attempted various methods such as grouping by and using a reduce function, but these approaches resulted in a condensed tree structure without the necessary inclusion of data and children attributes. Can someone advise on how to create the tree structure while retaining these attributes? Any assistance would be highly appreciated! Below is an example of the function I tried, which effectively created the tree structure but lost some essential data attributes:

  let result  = this.data.reduce(this.totree, {}); 

 totree(branches, node) {

    if (!branches[node.corpId]) {
      branches[node.corpId] = {};
    }
    branches[node.corpId][node.rela] = node;
    branches[node.corpId][node.rela] = Object.assign(branches[node.corpId][node.rela]);
    return branches;
  }

Answer №1

I have written and tested this code specifically for you. While I believe there is room for refactoring, the most important aspect is that it fulfills the structure requirements you desired.

const arr = [
  { pk: "1", corpID: "1234", date: "31/03/21", rela: "4325", price: "20.00" },
  { pk: "2", corpID: "1234", date: "21/03/21", rela: "4425", price: "50.00" },
  { pk: "3", corpID: "3456", date: "03/03/21", rela: "6327", price: "80.00" },
  { pk: "4", corpID: "4567", date: "05/03/21", rela: "7328", price: "40.00" },
];

const groupBy = (arrayInput, key) => {
  return arrayInput.reduce(
    (r, v, i, a, k = v[key]) => ((r[k] || (r[k] = [])).push(v), r),
    {}
  );
};

const groupedByCorpID = groupBy(arr, "corpID");

const ans = Object.entries(groupedByCorpID).map(([key, value]) => {
  const groupedByRela = groupBy(value, "rela");

  const children = Object.entries(groupedByRela).map(
    ([childKey, childValue]) => {
      return {
        data: { RELA: childKey },
        children: childValue,
      };
    }
  );

  return { data: { corpID: key }, children };
});

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

Adding the node_modules directory to a global npm package: A step-by-step guide

I've developed an npm package with numerous dependencies. However, when I test my app using npm install -g ./, the application is added to the global npm directory without the node-modules folder. As a result, when the app is launched from the termina ...

Sending a $.ajax post request transforming into a get

Struggling to understand the behavior of my jquery ajax request, I've hit a roadblock. function newContact() { $.ajax({ type: 'POST', contentType: 'application/json', // url: ...

Selecting tabs in Angular with a controller function

I'm currently working on implementing AngularJS to show the tab number when a specific tab is selected using the controller method. However, it's not working as expected. Any assistance on this issue would be greatly appreciated. HTML <body ...

css rules are not applied if the element is dynamically added using javascript

I'm encountering an issue with my code that inserts icons into a div with the ID of "editor". When I try to add a <select> element to the div with the ID of "drug_tool", the CSS styling rules for it are being ignored. How can I resolve this prob ...

Message successfully sent despite Ajax failure

Hello everyone, I'm currently facing an issue while trying to send a message using the form craft plugin. The error message that I am encountering is " 504 (Gateway Time-out)" along with some technical details: send @ jquery.js:4 ajax ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page: // ==UserScript== // @name _Modify select Google search links // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @include http://62.0.54.118/* // ==/Us ...

Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

Using Angular to Bind Checkbox Value in Typescript

I have a challenge of creating a quiz where a card is displayed with 4 questions structured like this: <div class="col-md-6"> <div class="option" id="Answer1"> <label class="Answer1"> <input value= "Answer1" type="checkbox ...

Is there a way to change the border property of an element when clicked, without causing the displacement of other elements?

I'm in the process of creating a webpage where users can choose the color and storage capacity of an item. Only one color/capacity can be selected at a time, and once chosen, it should be highlighted with a border. The issue I encountered is that whe ...

An example of using quotes within quotes is an HTML tag embedded within JavaScript code

Currently, I'm working on a JavaScript code where clicking assigns the function getImage the source of an image to be displayed later on the page. The issue I'm facing revolves around dealing with quotation marks. <img src="bill.jpg" class=" ...

Trouble with downloading files using the anchor (a) tag in React

Every time I try to click on the a tag to download the file named approved_leads.zip, I keep receiving an error message saying "failed - no file". It seems like the path is correct, so I'm not sure what is causing the issue. <a href="../../ass ...

Send a request from my own local client without encountering any Cross-Origin Resource Sharing (C

I am attempting to send a request from my locally hosted Node.js/Express.js client to a third-party API that I have deployed on the cloud. Strangely, I keep running into a CORS error whenever I make the request. The interesting part is that the request wor ...

.htaccess file is causing js and css files to not load

I followed an MVC tutorial by howcode on YouTube, but I encountered an issue where my CSS and JS files were not loading due to the htaccess configuration. .htaccess file: RewriteEngine On RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA] I attempted vario ...

Tips for cropping an image using CSS with dimensions specified for width, height, and x and y coordinates

As I work on implementing a cropping feature using react-easy-crop, my goal is to store the user's image along with pixel coordinates that dictate their preferred cropping area. My objective is to utilize the parameters provided by react-easy-crop in ...

Troubleshooting issue with asp.net jquery datepicker functionality

Having recently delved into the world of JavaScript and jQuery, I'm encountering some issues that I can't seem to resolve. My gut feeling is that the problem lies in the reference to the jQuery files not working properly, but I could be mistaken. ...

What is the solution to resolving a Typescript error within an imported library?

I've encountered a Typescript error that I'm unable to resolve because it doesn't originate from my code. The issue arises when I import a NextJs/React module named next-seo and use it as instructed: <NextSeo config={seoConfig} /> The ...

Displaying a 404 error page in a Vue.js and Vue Router single-page application when a resource is not

Implementing Vue and Vue Router in a single page application (SPA) has presented me with a challenge. In one of my view components, I query a repository for a specific resource. If the resource cannot be found, I'd like to display a 404 error page wit ...

Consistently encountering the message 'Error: timeout of 2000ms exceeded' while using Selenium

Good morning, Currently, I am in the process of learning how to use Selenium with JavaScript (specifically using Mocha). I have created a very basic test that is causing some issues during runtime. Whenever I run the test, a new instance of Chrome opens a ...

JavaScript - returning a false error

I'm experiencing an issue with my form validation function that is supposed to check for empty fields by looping through the form elements. Here's the code snippet: function validateForm(ourform){ var formElements = document.getElementById(our ...