Organize an array of objects into a custom tree structure with the data arranged in reverse

I have an array of objects structured as key value pairs with children forming a tree. For a clearer understanding, please see the attached screenshot.

Despite trying various methods, I have been unable to achieve the desired result shown in the image.

Answer №1

You have the option to categorize by the specified keys and generate an array containing the desired groupings for each level.

const
    data = [{ HLT: "Infections NEC", LLT: "Adrenalitis", HLGT: "Infections - pathogen unspecified", PT: "Adrenalitis", SOC: "Infections and infestations" }, { HLT: "Adrenal neoplasms", LLT: "Adrenal cyst", HLGT: "Adrenal gland disorders", PT: "Adrenal cyst", SOC: "Endocrine disorders" }, { HLT: "Adrenal gland disorders NEC", LLT: "Adrenal mass", HLGT: "Adrenal gland disorders", PT: "Adrenal mass", SOC: "Endocrine disorders" }, { HLT: "Adrenal gland disorders NEC", LLT: "Adrenomegaly", HLGT: "Adrenal gland disorders", PT: "Adrenomegaly", SOC: "Endocrine disorders" }, { HLT: "Adrenal gland disorders NEC", LLT: "Adrenal nodule", HLGT: "Adrenal gland disorders", PT: "Adrenal mass", SOC: "Endocrine disorders" }, { HLT: "Adrenal gland therapeutic procedures", LLT: "Adrenalectomy...

// The rest of the code remains the same with no changes made 
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Take a look.

const dataset = [
  {
    "Type": "Fruit",
    "Variety": "Apple",
    "Category": "Fresh Fruits"
  },
  {
    "Type": "Vegetable",
    "Variety": "Carrot",
    "Category": "Fresh Vegetables"
  },
  {
    "Type": "Berry",
    "Variety": "Blueberry",
    "Category": "Berries"
  }
];


const treeData = {
  name: "My Produce Tree",
  children: []
};

dataset.forEach((item) => {
  let currentNode = treeData;
  ["Category", "Type", "Variety"].forEach((key) => {
    let childNode = currentNode.children.find((child) => child.name === item[key]);
    if (!childNode) {
      childNode = { name: item[key], children: [] };
      currentNode.children.push(childNode);
    }
    currentNode = childNode;
  });
});

const width = 800;
const height = 600;

const svg = d3.select("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(40,0)");

const tree = d3.tree().size([height, width - 160]);

const root = d3.hierarchy(treeData);
tree(root);

const link = svg.selectAll(".link")
  .data(root.links())
  .enter().append("path")
  .attr("class", "link")
  .attr("d", d3.linkHorizontal()
    .x((d) => d.y)
    .y((d) => d.x));

const node = svg.selectAll(".node")
  .data(root.descendants())
  .enter().append("g")
  .attr("class", "node")
  .attr("transform", (d) => `translate(${d.y},${d.x})`);

node.append("circle")
  .attr("r", 4.5);

node.append("text")
  .attr("dy", ".31em")
  .attr("x", (d) => d.children ? -13 : 13)
  .style("text-anchor", (d) => d.children ? "end" : "start")
  .text((d) => d.data.name);
.node circle {
    fill: #fff;
    stroke: steelblue;
    stroke-width: 1.5px;
  }

  .node text {
    font: 12px sans-serif;
  }

  .link {
    fill: none;
    stroke: #ccc;
    stroke-width: 1.5px;
  }
<script src="https://d3js.org/d3.v7.min.js"></script>
<svg width="960" height="600"></svg>

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

Setting the sidebar width for Nebular with two sidebars in the layout: A step-by-step guide

Having two sidebars (identified as left and right) in my page layout, I initially set both sidebars to a width of 400px using the custom theme method with sidebar-width: 400px. However, I now need to change the width of the right sidebar to 700px. Is the ...

Converting JSON to a list using JavaScript

As a beginner in JavaScript, I apologize for asking possibly a redundant question. Can someone guide me on the most effective way to parse json? I am specifically interested in extracting a list of strings under the name Maktg: { "d":{ "res ...

Determine the exact beginning and ending positions of a word when dividing it using Javascript

After creating a special function that breaks down a word based on spaces while keeping punctuation marks intact, I was able to achieve the desired result. function tokenizeUtterance( utterance ) { let spilittedUserText = utterance.toString().match( /[& ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

While working on my Python currency converter project, I encountered an issue where the program returned an error stating that the variable 'money' was not defined, despite previously defining it. This problem arose specifically during

usd = 2 yen = 1000 gbp = 1.7 eur = 0.75 def again(): selection = False while selection == False: amount = input("Please enter an amount ") try: int(amount) except ValueError: print("Invalid: Please ...

Algorithm-driven dot selector

We are currently utilizing ReactJS and MaterialUI for our frontend development. We are facing a challenge with a specific component, unsure of whether it should be a slider (https://material-ui.com/components/slider/), stepper (https://material-ui.com/comp ...

Creating a responsive image within a panel using Bootstrap

I've been struggling to make a responsive image fit inside a panel while maintaining its aspect ratio and ensuring none of it gets cut off. I've attempted various CSS tweaks with no success. My setup involves Bootstrap along with React.js using r ...

Calculate the variance between two variables

I am facing a challenge where I have an object and the 'Hours' field is saved as a string. I am looking to convert this string into actual hours and then calculate the difference between the two variables. const groupSchedule=[ {"days":"sat" ...

The issue persists with Jquery's removeData function when used on a modal triggered by an href link in order to transmit $_GET

I am currently developing a website that dynamically populates a table from the database. Each row in the table contains a button that triggers a modal to display more details and allows for database updates. To pass the required values to the modal, I hav ...

In JavaScript, when the search input is empty, all items in the array are displayed

I want to ensure that if the input field is empty, no results are displayed. Currently, when you enter a name and then delete it, all the results in the array are shown. const characters = [{ first_name: "Abraham", last_name: "Lincoln", img: ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

How to effectively handle multiple conditional statements in TypeScript?

I attempted to implement a "multiple filter" feature in TS, so... If I don't provide any input -> all products are returned as usual; However, if I specify some parameters -> only products matching the parameters are returned. (I us ...

Create a fresh array by merging two existing arrays together

My project involves working with two separate arrays. The first array contains normal date values: var = [ "2022-05-01", "2022-05-02", ... "2022-05-30" ] The second array consists of objects that contain s ...

Eliminate unnecessary components during the JSON to CSV conversion process

I have a JSON data set that looks like this: {"id":1,"name":"Sam","birthday":"12December","age":"15"}, {"id":2,"name":"Ash","birthday":"12January","age":"23"} After passing the data through the function: ConvertToCSV(data) I can extract id, name, birth ...

The NestJS HttpException class will default to a status code of 201 if no specific status code is

This particular instance showcases how instantiating the HttpException class in this manner results in an exception being thrown with an undefined status, ultimately becoming a status of 201 (I presume it defaults to this status as it is associated with a ...

Can you identify the data structure of my array?

I need help with the function I'm working on: int** myfunc() { int array[2][2]; // operations on the array return array; } The compiler is showing the following error message: cannot convert 'int (*)[2]' to 'int**' i ...

Potential Scope Problem in Angular JS Controller

The HTML code snippet I have is as follows: <body ng-controller = "Control as control"> <button ng-click = "control.prepareAction()">Do Action </button> <div id="one" ng-hide = "!control.showOne" > <div> <h6> ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

In React Js, the state is being updated correctly when console logging, however, the user interface is not reflecting

Recently, I encountered an issue with updating the UI after clearing the input states in my object. Despite setting the input values to empty strings upon clicking the clear all button, the UI does not reflect these changes as expected. The initial state ...