Struggling to organize data into a hierarchy using the D3.js nest function

Attempting to build a d3.js tree, I need my data to be in hierarchical form before using d3.treeLayout.

Currently, here is what my json array looks like:

var data = [
      {"group":"1","price":"36599.88", "cy":"44260"},
      {"group":"2","price":"36599.88", "cy":"44260"},
      {"group":"3","price":"36599.88", "cy":"44260"},
      {"group":"4","price":"36599.88", "cy":"44260"},
      {"group":"1","price":"1241.88", "cy":"44260"},
      {"group":"2","price":"36595429.88", "cy":"44260"},
      {"group":"3","price":"12124.88", "cy":"44260"},
      {"group":"4","price":"6264.88", "cy":"44260"},
    ]

Utilizing the d3.nest() function to group the entries:

var NestedBudget = d3.nest()
                    .key(function(d){
                        return d.group;
                    })
                    .entries(data);

Unfortunately, this structured data does not work when passed to d3.hierarchy(). https://i.sstatic.net/913jy.png

I have included an image of the result obtained after passing it to

var root_data = d3.hierarchy(data);

I hope this explanation is clear. Any assistance would be greatly appreciated.

Answer №1

Always keep in mind the importance of having a tree structure. A tree must have a root element and each node should possess two essential attributes: a unique identifier and a reference to its parent's identifier.

By incorporating an id field and assuming that "group" signifies the parent node, you can reorganize your flat data into a hierarchical format :

var data = [
      {"id":"0", "group":null, "price":"36599.88", "cy":"44260"},
      {"id":"1", "group":"0", "price":"36599.88", "cy":"44260"},
      {"id":"2", "group":"0","price":"36599.88", "cy":"44260"},
      {"id":"3", "group":"0","price":"36599.88", "cy":"44260"},
      {"id":"4", "group":"0","price":"36599.88", "cy":"44260"},
      {"id":"5", "group":"1","price":"1241.88", "cy":"44260"},
      {"id":"6", "group":"2","price":"36595429.88", "cy":"44260"},
      {"id":"7", "group":"3","price":"12124.88", "cy":"44260"},
      {"id":"8", "group":"4","price":"6264.88", "cy":"44260"},
    ];

const tree = d3
      .stratify()
      .id(d => d.id)
      .parentId(d => d.group)(data);
      
console.log(tree);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

It is worth noting that the node with "group":null serves as the root node (as per definition, a root node marks the starting point of the tree and hence lacks a parent).

Answer №2

Alright, Pierre Capo's observation was spot on. I included the variable

packableData = {id:"parent", values:data};

into the data that I'm currently getting, which will establish the parent within the hierarchy when it is passed to d3.hierarchy()

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

Retrieve information from MySQL database to display in Android application

I am trying to retrieve data from a MySQL database using PHP and display it in an Android activity. I have coded it to pass a JSON Array, but I am encountering a problem connecting to the server because my database is located on a local server. Can someone ...

Combining Argparse and Json: A Powerful Duo

I am new to Python. I'm curious if Argparse and JSON can work together. For example, let's say we have variables p,q,r We can add them to argparse like this - parser.add_argument('-p','--param1',help='x variable' ...

issue with duplicating DOM element using function

My situation is unique from the one described in this post. The code mentioned there is not functioning as expected when clicking the clone button. I have even provided a video explanation of how that code works. Unfortunately, I haven't received any ...

What is the process for changing the text in a text box when the tab key on the keyboard is pressed in

When a user types a name in this text box, it should be converted to a specific pattern. For example, if the user types Text@1, I want to print $[Text@1] instead of Text@1$[Text@1]. I have tried using the keyboard tab button with e.keyCode===9 and [\t ...

Comparing values in an NSDictionary on iOS

section: An important task at hand involves retrieving and storing two distinct sets of JSON data as NSArray and NSDictionary, respectively. Here is a glimpse into the structures of these JSON data: ( { Cells = ( { ...

When a string begins with the "<" character, jQuery regex is unable to find a match

I am attempting to check if a string starts with the "<" character, but I am running into issues. The expression works perfectly fine on regex101.com, however, it fails when used in my personal files. When I input a backslash everything works as expect ...

Generating random numbers within specified character limits using Javascript and Selenium

Just starting to learn javascript - I am working on creating random user IDs for my selenium test scenarios. The line of code I am using for the value is as follows: javascript{Math.floor(Math.random()*11111)} However, there is a specific field that need ...

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

How to customize the arrow color of an expanded parent ExpansionPanel in material-ui

Currently facing a challenge in customizing material-ui themes to achieve the desired functionality. The goal is to have the expansion panels display a different arrow color when expanded for improved visibility. However, this customization should be appl ...

Determine if the input number exceeds a specified threshold by implementing JavaScript

My attempt at performing calculations on a page is not yielding the desired results. I have tinkered with the code below, but it doesn't seem to be working as expected. Can anyone provide guidance on where I might be going wrong? Specifically, I want ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Why does tween animation appear instant rather than smooth?

I am trying to achieve a camera movement effect where the camera transitions from its current position to the center of a mesh (which is a sphere and I want to be inside of it) when a button is clicked. I have implemented a function with a tween for this ...

The functionality for tabbed content seems to be malfunctioning on Chrome and Firefox, however it works perfectly

In my index.js file, I have various functions set up like so: // a and b is placed at index.jsp $("#a").click(function (){ //this works on index.jsp and display.jsp(where the servlets forwards it). $("#b").load('servletA.html?action=dis ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

Monitor the elements displayed as you scroll

Thank you for taking the time to read this. I am currently working on a webpage that features a top Calendar component displaying a week, and below that is a Scroll component showing detailed information for each day of the week. Here is what my page loo ...

problem encountered when transferring data using ajax

I'm struggling with figuring out how to use an ajax function My goal is to send PHP variables via ajax to another page when a user clicks on a link Javascript function sendData(a, b, c, d) { $.ajax({ url: "page.php", typ ...

A step-by-step guide on using the smartsheet API to recursively fetch folders

I'm currently developing a Python backup tool for Smartsheet. My goal is to extract all the user files within my domain. However, I am unsure of how to retrieve this data while maintaining the hierarchical structure of folders as shown below: Folder ...

With Ionic, you can use one single codebase for both iPad and iPhone

I currently have a complete app developed using ionic and angularjs that is functioning well on iPads and Android devices. Now we are looking to launch it for iPhones and Android smartphones with some design modifications. Is there a method to achieve th ...

Anticipated a task or method invocation but encountered an expression instead no-unused-expressions (line 14/15)

I can't seem to figure out the issue with my code. Despite trying to fix it multiple times by adjusting lines 14/15, I keep encountering the same error. If anyone has any insights or suggestions on what might be causing this problem, I would greatly a ...

Prevent automatic scrolling to the top following an AJAX request

Question about Preventing Scrolling to Top: How can I prevent a web page from scrolling to the top when a link triggers javascript? Whenever an ajax request occurs, my browser automatically scrolls to the top. In order to return to my desired div sect ...