Utilize the nest function in D3 to organize flat data with a parent key into a hierarchical structure

I'm searching for an elegant and efficient solution to transform my input data into a hierarchical structure using d3.js nest operator. Here is an example of the input data:

[
{id: 1, name: "Peter"},
{id: 2, name: "Paul", manager: 1},
{id: 3, name: "Mary", manager: 1},
{id: 4, name: "John", manager: 2},
{id: 5, name: "Jane", manager: 2}
]

What I aim to achieve is a hierarchy layout like the one shown below:

[ 
   {name: "Peter", children: [
          {name:"Paul", children: [
              {name:"John"},
              {name:"Jane"}
          ]},
          {name:"Mary"}
      ]
   }
]

Answer №1

Using the nest operator in this scenario is not recommended as it creates a fixed hierarchy with the same number of levels as key functions specified.

However, a custom function can be created to build a tree structure. By treating the first node in the input array as the root node and mapping nodes to their respective ids, the tree can be lazily constructed.

function createTree(nodes) {
  var nodeById = {};

  // Index nodes by id for unordered input.
  nodes.forEach(function(node) {
    nodeById[node.id] = node;
  });

  // Construct children nodes as needed.
  nodes.forEach(function(node) {
    if ("manager" in node) {
      var managerNode = nodeById[node.manager];
      if (managerNode.children) managerNode.children.push(node);
      else managerNode.children = [node];
    }
  });

  return nodes[0];
}

If the nodes are ordered such that managers precede their reports, the code can be optimized for single iteration.

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

What is the process for saving an HTML document with SaveFile.js?

I'm currently implementing a save feature for my website. Utilizing the 'SaveFile.js' module from this link: 'https://github.com/eligrey/FileSaver.js/' Once the user clicks on the save button, the goal is to have the entire documen ...

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...

Enhance DataTables functionality by including the ability to select which script to execute

Currently, I have a DataTables displayed with the provided code, utilizing server-side processing which is functioning properly. I am interested in implementing a dropdown menu above the table that allows users to select from options such as: Product Gr ...

The average duration for each API request is consistently recorded at 21 seconds

It's taking 21 seconds per request for snippet.json and images, causing my widget to load in 42 seconds consistently. That just doesn't seem right. Check out this code snippet below: <script type="text/javascript"> function fetchJSONFil ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

Should I refrain from storing user files on my server?

Greetings! I am currently working on an Express js + React js application and using MySQL for database management. I have successfully stored user information like email, hashed passwords, and user IDs in the database. However, now I want to create ...

I possess a variety of poppers and desire for the opened one to close when another one is opened

Having built a component that generates 6 unique experiences, each with its own popper containing images, I am struggling to figure out how to modify my code so that one popper closes when another is clicked. Here is the current setup: This is the compone ...

Canvas ctx.drawImage() function not functioning properly

I've encountered an issue while trying to display images in a canvas using my rendering function. Here is the code snippet: function populateSquareImages(){ for(var i = 0, ii = squares.length; i < ii; i++) { if(squares[i].hasImage) { ...

Configuring Firefox settings in Nightwatch

Is there a way to set Firefox preferences in nightwatch? I am trying to achieve the same thing in Java using nightwatch. To set Firefox preferences in nightwatch, you can use the following code snippet: FirefoxProfile profile = new FirefoxProfile(); prof ...

Mouse hovering over the JS slider activates the sliding functionality, while removing the cursor

Hi there, I'm encountering some issues with the JS clients slider on my website. I need to pause it when the mouse is over and resume when the mouse leaves. I've double-checked the code but for some reason it's still not functioning properl ...

Retrieve images from the API

Currently, I am working on an e-commerce application using the Moltin.com SDK. Although I have followed the documentation accurately, I am facing an issue regarding loading multiple images of a single product in a table view with a custom cell. Below is th ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

Using Java's Jackson streaming API to establish a connection using TCP sockets

Having trouble with sending and receiving JSON objects over a socket connection. The parsing is not working correctly on the server side. This project marks my first attempt at Java programming. Below is my socket class: static class CheckerSocket im ...

"Cookie Magic: Unleashing the Power of Ajax and

I am currently working on an ASP.NET 3.5sp1 application with a single page layout where all interactions are handled through ajax, eliminating the need for postbacks. The website in question is . This app does not require user accounts and allows anonymou ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

What is the process of utilizing marked plugins within a Vue3 project?

I attempted to integrate the marked plugin into my Vue.js applications. After installing [email protected], I did not encounter any issues during compilation. However, when I viewed the contents in the browser, nothing appeared. My Vue project was built u ...

Are there alternative methods for anchoring an element in Vuetify aside from using the v-toolbar component?

I have been working on positioning certain elements in the app and I have found a method that seems to work, using code like this: <v-toolbar fixed></v-toolbar> Another option is something along these lines: <v-toolbar app></v-toolb ...