Creating data for a sunburst chart using Javascript

I am looking to create a dynamic sunburst chart using echarts, specifically with a children -> grandchildren structure. I found inspiration from this example on the Echarts website. Initially, the data I received from the backend was in a flat format.

const data = [
  {
    region: 'EMEA',
    username: 'MG',
    priority: 'P3',
    application: 'G1',
    count: 1
  },
  ...
]

To build the child list dynamically, I have defined it as follows: const children = ['region','application','priority'];

I need guidance on how to aggregate this data into nested structures as shown below:

const dataSet =[
name: 'India', 
value: 16,
children:[
  {name: 'E5',
  value: 3,
     children:[
         {name: p3, value: 1},
         {name: p2, value: 2}
     
    ]
   },
   ...
]

Your insights and suggestions would be greatly appreciated. Thank you.

Answer №1

There is a method I have discovered (although it may not be the most efficient)...

const children = ['region','application','priority'];
const dataArray = new Array();
data.forEach((d, idx)=>{
                        const count = d.count
                        
                        children.forEach((child,index)=>{
                            const name = d[child];
                            const item = {name: name, value: count}
                            if(index === 0){
                                let temp = dataArray.find((o)=>{return o.name === name})
                                if(temp){
                                    temp.value += count
                                }else{
                                    dataArray.push(item)                                
                                }
                            }else{
                            
                                const previousKeys = children.slice(0, index)
                                const firstKey = previousKeys.shift()
                                const firstValue = d[firstKey]
                                let temp = dataArray.find((o)=>{return o.name === firstValue})
                                previousKeys.forEach((key,i)=>{
                                    const v = d[key]
                                    
                                
                                     temp = temp.children.find((o)=>{return o.name ===v})
                                    
                                     
                                
                                     
                                
                                
                                });
                                
                                
                                if(!temp.children)
                                {
                                     temp.children = new Array()
                                 }
                                 
                                 let m = temp.children
                                 let n = m.find((o)=>{return o.name === item.name})
                                 if(n){
                                    n.value += item.value
                                 }else{
                                    m.push(item)
                                 }
                                
                            }
                        
                        });
                        
                        
                    });

An important aspect to note is that when constructing the next level, the previous level must already have been constructed. This concept is utilized in the `previousKeys.forEach((key,i)=>{}` loop. It shifts the `temp` variable to the "just one level up" of the current `item`, and then checks for the existence of the `item` name to determine whether to add a new item or merge it into an existing slot.

The `children` variable dictates the sequence and hierarchy levels of the sunburst chart (from innermost to outermost).

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

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

JavaScript - Populate canvas with selected image from gallery upon clicking an image

A photo gallery on my website is filled with images fetched from a local directory using PHP. I would like users to be able to select an image by clicking on it and then have the option to draw on that image within a canvas element. The gallery has been c ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

Node.js Sparse Array Memory Usage Explained

I created a program that generates arrays and noticed an interesting behavior: var results = []; var i = 1; while (true) { console.log(i++); results.push([]); } However, when I modify the program to create sparse arrays instead of empty ones, it cra ...

Dealing with ASP.NET forms that involve a javascript plugin generating substitute input

I'm facing an issue with my ASP.NET MVC webpage where I submit a form using AJAX in the following way: function ValidateFormAndAjaxSubmit(formId, callingElement) { if (IsNotDblClick(callingElement.id)) { var _form = $("#" + formId); ...

What is the best way to send multiple input box values to a function set in the controller?

I am attempting to send the values of two input boxes to a single controller function. <div class="container" ng-controller="MainCtrl"> <div class="row"> <div class="col-lg-6"> <input type="text" ...

Does applying a style to an element that already has the same value result in a decrease in performance? Alternatively, do all browsers simply overlook it?

Assuming I have an element with the style top: 5px, and then I execute element.style.top = "5px";, will the browser readjust its position and trigger a layout again? Or does it recognize that there is no need to change anything? (Is this behavior specified ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Javascript string manipulation operation

Is it possible to extract only the characters 'ABCD' from a string like 'ABCD150117T15' using JavaScript? I am interested in removing everything after 'ABCD' in this example, specifically excluding the first occurrence of a n ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

Utilizing jQuery and JSON to showcase the contents of an array

My goal is to display all the items in an array by utilizing JSON and jQuery from the Song of Ice and Fire API. Currently, I am only able to display one item from each of the arrays. If you want to view the codepen, click here: https://codepen.io/frederic ...

Using AngularJS to automatically include predefined data in an $http request

I am looking for a way to include a default data attribute in an http request. I came up with the following code: var app = angular.module('dumbhttp', []); app.service('dumbhttp', function ($http, $location) { this.post = function ...

Adding input fields that change dynamically along with their corresponding radio buttons using AngularJS

Hello, I am struggling with implementing a feature in my HTML and AngularJS files (using Bootstrap ui). I want to create a new input field (td) along with three corresponding radio buttons when the user clicks on an add button. I have attempted to modify t ...

What method can be used to verify if Handlebar.js is integrated into the application?

I am struggling to verify the presence of Handlebar JS on the application's HTML page. No matter what I do, it keeps throwing an error saying "Uncaught Reference Error - Handlebars is not defined". Can anyone provide guidance on how to fulfill this ta ...

When using Vue.js, pressing the enter key will automatically insert a <br> tag into the text output

I am in need of implementing basic text editor functionality into an application. I currently have a textarea where user input is reflected in a paragraph. I have implemented event listeners for spacebar and enter key presses within the textarea to trigg ...

Invoking a bean using a Javascript Birt Expression

I am attempting to display the contact number (GetExtension) of the current user logged in and generating a report. The following code successfully displays the name of the logged-in user when placed within Birt's Expression Builder (Dynamic text fie ...

Using the prop callback in a React test renderer does not trigger updates in hooks

I am currently exploring ways to effectively test a React function component that utilizes hooks for state management. The issue I am encountering revolves around the onChange prop function not properly updating the state value of my useState hook. This in ...