Creating a hierarchical JSON layout for constructing dual d3.js graphs side by side

I am currently struggling with navigating through a JSON structure that I created in order to generate side-by-side donut charts. I suspect that my structure is not ideal and would greatly appreciate any guidance.

My inspiration comes from Mike Bostock's example found here: http://bl.ocks.org/mbostock/1305337, where he utilizes a .csv file for the data source.

In his example, Bostock uses d3.nest() to construct a nested data format with an array of flight origins:

  var airports = d3.nest()
      .key(function(d) { return d.origin; })
      .entries(flights);

He then connects this new data format to a specific div element using D3 selection:

 var svg = d3.select("body").selectAll("div")
  .data(airports)
.enter().append("div")

This allows him to create a donut chart for each unique flight origin.

The structure of my JSON data appears as follows:

{"years": [
  {
    "year": 2015,
    "type": "bestSellers",
    "chartOne":  [
        {
          "label": "smarties",
          "value": 11
        },
        {
          "label": "nerds",
          "value": 13
        },
        {
          "label": "dots",
          "value": 16
        },
        {
          "label": "sour patch kids",
          "value": 61
        }
    ],
    "chartTwo": [
        {
          "label": "Pepsi",
          "value": 36
        },
        {
          "label": "sunkist",
          "value": 13
        },
        {
          "label": "coke",
          "value": 34
        }
    ]}

Being a computer science student with limited exposure to data structuring principles and d3.js, the hierarchy I have designed does not appear straightforward to me. Unsure if utilizing d3.nest() is necessary, I struggle with accessing data within chartOne and chartTwo using the current structure.

While I can reach the arrays within the charts with:

var chartOne = years[0].chartOne; var cartTwo = years[0].chartTwo;

I aim to access both charts through a single object. Contemplating adding another array block to my JSON, I wonder if there might be a simpler solution available.

Answer №1

There is no need to utilize .nest in this scenario. The most straightforward way to construct the necessary data structure is as follows (since d3 always expects an array to iterate over):

var nestedData = [ years[0].chartOne, years[0].chartTwo ];

After that, all you need to do is refine the accessor functions for your data, and Bostock's example should work effectively.

Check out the example here.

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

Struggling to fetch information from API through Express in NodeJS with MongoDB, currently loading

I am in the process of creating a Rest API using Node.js, Express, and MongoDB. Currently, I am running it on my local host:3000. When I attempt to restart and run the server, I utilize the route http://localhost:3000/drinks To send HTTP requests, I use P ...

How can I upload a folder with subfolders and keep the structure intact?

I'm working on a form that allows me to upload a folder containing both files and subfolders with more files inside. I managed to upload the folder successfully, but when I check my directory, all the files are in one folder without the subfolders. My ...

Transform one column into several columns

I am working with a function that populates a table row by row. Here is the code: function renderListSelecoes(data) { // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one') va ...

What could possibly be causing the "Unexpected token (" error to appear in this code?

Sorry if this appears as a typo that I am struggling to identify. My browser (Chrome) is highlighting the following line <a class="carousel-link" onclick="function(){jQuery('#coffee-modal').modal('show');}">Book a coffee</a> ...

Material-UI exclusively incorporates specific components

Is there a way to include Material UI dialogs in my project without having to install the full Material UI library? I only need the dialogs component and don't want any other components included. Any suggestions or help on how to achieve this would be ...

Using PHP to retrieve data from a JSON file (obtaining blank results containing numerical values)

I'm attempting to extract data from a JSON file using PHP I am interested in retrieving all URLs (links), http://www.google.com http://www.bing.com JSON https://i.sstatic.net/nOx6A.jpg This is what I have attempted so far PHP https://i.sstati ...

What causes JSONiq to only return the last element?

View my json and query images here https://i.sstatic.net/FbJ0y.png Here is the Json code: { "reading_list": { "book": { "name": "Fifty shades of grey", "author": "E.L James", "date": "March 2015", ...

Display Image based on AngularJS value

Within my data, there exists a value {{catadata2.EndorsementList['0'].Rating}}. This value can be either 3, 4, or 5. Based on this value, I am looking to display the image <img src="/assets/img/rating.png" /> a certain number of times. For ...

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

Transferring information from one page to the next

How can I efficiently transfer a large amount of user-filled data, including images, between pages in Next.js? I've searched through the Next.js documentation, but haven't found a solution yet. ...

The addition of days is producing an incorrect result

When extracting the date from FullCalendar and attempting to edit it, I noticed that moment.js seems to overwrite all previously saved dates. Here is an example of what's happening: var date_start = $calendar.fullCalendar('getView').start.t ...

Retrieve items from the parent row of selected checkboxes

Within my table, I have the following row. <tr class="data_rows" ng-repeat='d in t2'> <td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td> &l ...

Utilizing numerous Nuxt vuetify textfield components as properties

Trying to create a dynamic form component that can utilize different v-models for requesting data. Component: <v-form> <v-container> <v-row> <v-col cols="12" md="4"> <v ...

What could be causing the responsive line chart from nivo to not appear in jsdom while using Jest?

I am currently working on writing UI tests for my application using Jest/Testing Library. In the testing process, I have integrated the ResponsiveLine component from the @nivo/line library. However, I am facing an issue where the Responsive Line componen ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

A guide on extracting individual Json fields and assigning them to separate variables

I have a JSON object that I need to break down into individual fields and then use each field separately. However, the code I wrote below is not functioning correctly and returns "undefined" in the alert message. This is my code snippet: $( document ).r ...

Retrieve the value from an input field when the value is returned from JavaScript

Scenario: I'm currently working on creating a QR reader to retrieve a specific value. You can check out the progress here: What's functioning: scanning. When I scan a QR code, a value is displayed in the text box. Here's the code snippet b ...

Passing a reference to a react functional component (react.FC) results in a type error: The property ref is not recognized on the type 'IntrinsicAttributes & Props & { children: ReactNode}'

Currently, I am working on mastering the utilization of forward refs. In a functional component (FC), I am trying to initialize all my refs and then pass them down to its child components so that I can access the canvas instances of some chartjs charts. Ho ...

The ng-click event for the reset button is limited to a single use

There seems to be a problem with the reset button functionality on my webpage. Although it initially works, it only works once and then requires a reload of the page to function again. Here is the JS code: var ctrl = this; var original_device = angular.c ...

Adding elements in increasing order based on the array values

I am implementing selectize.js, where the data is added through an array. My goal is to display the dropdown list in the order of DISPLAYORDER defined within the object. The code below generates the lists: option: function(item, escape) { var popular ...