Converting an array JSON into a hierarchical tree structure of objects in Angular

Looking to transform a JSON into a tree structure of objects. Consider the following example:

    {
    "id": 2,
    "label": "BEAUTY",
    "description": "",
    "parent_id": 0,
  },
  {
    "id": 5,
    "label": "SunGlass",
    "description": "",
    "parent_id": 2,
  },
     {
    "id": 6,
    "label": "Shirts",
    "description": "",
    "parent_id": 2,
  },
  {
    "id": 41,
    "label": "black Glasses",
    "description": "electronique",
    "parent_id": 5,
  },
    {
    "id": 34,
    "label": "T-shirts",
    "description": "electronique",
    "parent_id": 6,
  },
    {
    "id": 3,
    "label": "Phones",
    "description": "",
    "parent_id": 0,
    "embedded_parent": null,
  }
 

The goal is to convert this list into a tree object based on the 'label' attribute. The expected result looks like this:

const TREE_DATA = {
  BEAUTY: {
    'SunGlass': {'black Glasses':null},
    'Shhirts': null,
    
  },
  Phones: {
      'Sbardilate': null,
      'T-shirrrrsees': null,
      'Balons': null,
  },
  
};

A recursive function is needed to achieve this result, in order to pass it to my Angular component widget efficiently. Thank you for your help!

Answer №1

As mentioned by @jonrsharpe, it's important to share your solution and explain where you're facing challenges instead of just copying answers from StackOverflow.

To tackle your specific issue, consider creating interfaces to streamline development. For the Node, a recursive interface can be defined like this:

interface Item {
  id: number,
  label: string,
  parent_id: number,
  description: string
}

interface Node {
  [label: string]: Node | null;
}

Another step is to group elements based on the parent_id. This allows quick access to all information within a Node using groupedByParentId[id] with an O(1) access time.

const groupedByParentId = array.reduce(
  (acc, cur) => {
    const parentId = cur.parentId;
    const groupedItems = acc[parentId] == [];
    return {...acc, [parentId]: [...groupedItems, cur]}
  },
  {} as {[id: string]: Item[]}
);

Creating a function to establish a starting point for the tree root is also beneficial:

const rootNodeId = 0;
function makeTree(): Node {
  const node = makeNode(rootNodeId);
  return node;
}

The next step involves implementing the makeNode function. Since you're venturing into this challenge independently, here are some hints to guide you through:

  • The function signature should be makeNode(id: number) and it should return a Node
  • Retrieve children of the current node using the provided data structure
  • If there are no children, you have your answer already ;)
  • If there are children, create a node for each one and store it in a property specified by the label
  • Lastly, return the node

Best of luck! :)

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 Next Js version "next" is at "14.2.3", indicating that the page is experiencing issues

After creating a project in Next.js version "14.2.3", I encountered this page with an error message. Surprisingly, I hadn't made any changes to my code when this occurred. https://i.sstatic.net/UcTnF3ED.png What could be the reason for this sudden i ...

Oops! Looks like there's a problem with the syntax - the import statement can't be

I encountered an error while trying to create Sequelize migrations in my Node.js app (which is set up with Typescript). When running npx sequelize-cli db:migrate, I received an "import method" error, but I'm unable to pinpoint the source of this issue ...

Utilizing flot.js to showcase a funnel chart with an external JSON file as the data source

Trying to create a funnel chart using the Flot.js library with an external JSON file as input. The JSON file is being fetched successfully, but the chart is not being plotted. [ { "data": 10, "label": "a" }, { "data": 81, "label": "b ...

Tips for implementing react-select types in custom component development

Currently, I'm in the process of developing custom components for DropdownIndicator to be used on react-select with Typescript. However, I am encountering difficulties with the component's type due to my limited experience with Typescript. I wou ...

Detecting clicks outside of a component and updating its state using Typescript in SolidJS

Hi there, I am currently learning the SolidJS framework and encountering an issue. I am trying to change the state of an element using directives, but for some reason it is not working. Can anyone point out what I might be doing wrong? You can find the ful ...

Streamline JSON arrays into separate variables based on their respective categories

Received a JSON output from a PHP file with the following structure; [{"device_id":"9700001","sensor_value":"31.5","update_time":"2017-04-28 18:49:06"}, {"device_id":"9700002","sensor_value":"31.5","update_time":"2017-04-28 18:47:05"}, {"device_id":"97000 ...

Creating an efficient post request using retrofit

Currently, I am delving into the world of Retrofit as it appears to provide solutions to many of the challenges I face with JSON requests and their handling. It is clear that interfaces play a key role in defining the methods utilized, particularly when m ...

What could be causing the JSON data to not be successfully transformed into an array in this particular scenario?

Here is the code snippet I am currently working with: $json_body = $application->request->getBody(); /*echo "JSON Body : ".$json_body; die; prints following data : JSON Body : { “current_user_id”:901 "user_id":990 } */ $request_da ...

Initiating the ngOnInit lifecycle hook in child components within Angular

I am facing an issue with controlling the behavior of child components in my Angular application. The problem arises when switching between different labels, causing the ngOnInit lifecycle hook of the children components not to trigger. The main component ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Can you explain the significance of <this> within TypeScript generics?

Our application employs express along with TypeScript. While exploring their type definitions, I stumbled upon the following snippet and I'm curious about its meaning: export interface IRouter extends RequestHandler { all: IRouterMatcher<this& ...

Data sent from Angular does not reach the C# controller it is intended for

I am currently facing an issue with my Angular component method that is intended to send data to a C# Controller. Despite successfully retrieving data from the controller to Angular, I encounter a problem when attempting to send data back to the controller ...

Typescript: Streamline the process of assigning types to enum-like objects

One common practice in JavaScript is using objects as pseudo-enums: const application = { ELECTRIC: {propA: true, propB: 11, propC: "eee"}, HYDRAULIC: {propA: false, propB: 59, propC: "hhh"}, PNEUMATIC: {propA: true, propB: ...

The 'Content-Type' header cannot be defined for HTTP GET requests

I am currently working on setting up my GET requests to include the specific header: Content-Type: application/json Based on information from the documentation, I need to make the following adjustment: To customize these defaults, you can add or remov ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

Troubleshooting PHP for loop issues when working with arrays

I am currently trying to populate a select list with a specific category of options from a json file ('name' in this scenario). I have successfully imported the file and utilized some of the data in other parts of my code (see below), so I believ ...

Utilizing Angular to Wrap User Interface Components with HTML Tags

I'm in the process of developing a custom "wrapper" library for Angular Material UI within my application. This concept is discussed further in an informative article titled Should you wrap your UI components article The main goal behind this wrapper ...

Submitting an event on an Angular modal component

I recently created a modal component using the following template structure: <div class="header"></div> <div class="body"> <ng-content></ng-content> </div> <div class="footer" ...

I am attempting to transform this document into a JSON format and save its results in a separate file

I need assistance converting this specific file into a JSON format and saving the output to another file. {"Device_Value": 65, "Device_Parameter": "CPU", "Company_Id": "604fb5916f5231778e4d1738", "De ...

Executing POST calls to a Google Apps Script

Everything was running smoothly. I managed to set up an endpoint using Google Apps Script that allowed end users to send a message to me (or another contact) and receive a copy of that message as well. The code for the POST request looked something like ...