Include varying number of tags for each attribute in a data input sequence

I have a collection of objects structured like this:

all_data = [
 {  
    title: "Hello", 
    slices: { 
        A: 50, 
        B: 70, 
        C: 40
     }
 },
 {  
    title: "Goodbye", 
    slices: { 
        A: 100, 
        B: 80, 
        C: 50
     }
 },
 {  
    title: "My title", 
    slices: { 
        A: 100, 
        B: 80, 
        C: 50,
        D: 200
     }
 },

//continue.. ]

How can I divide these data sets into n groups with rectangles scaled accordingly to match the slice values? Despite my attempts so far, I'm at a standstill and need guidance.

d3.select("body")
.append("svg")
.data(all_data)
.enter()
.append("g")
.whatDoIDo()

I am struggling to figure out how to expand each item in the data structure to include multiple rectangle tags based on certain criteria.

Answer №1

To achieve this, one approach would involve iterating through the slices object to build an array that will be utilized in a new data join operation.

For instance, if we consider the dataset provided in your inquiry, you can generate a hierarchical structure of nested SVG and G elements with the following code snippet. The second data join leverages the data already associated with the g.title components:

    let svg = d3.select("body")
      .append("svg")

    let titles = svg.selectAll(".title")
      .data(all_data)
      .enter()
      .append("g")
        .attr("class", "title")

    let slices = titles.selectAll(".slice")
        .data(function(d) {
          let arr = []
          for (let [key, value] of Object.entries(d.slices)) {
              // construct an array using the key-value pairs from the slices object
              arr.push([key, value]);
            }
          return arr
        })
      .enter()
      .append("g")
        .attr("class", "slice")

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

Guide to setting up an admin state in your React app with Firebase integration

In my web application, I have implemented authentication using Firebase. The appbar in my application displays different buttons depending on whether a user is logged in or not. Now, I want to add another button to the appbar specifically for users who a ...

How to dynamically modify a list box with JavaScript

I have an index.html file with a select tag containing multiple options for a drop-down: <label for="edu">Education</label> <select id="edu" name="edu"> <option value="0">10th</option&g ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

Avoid creating empty blocks in ASP.NET MVC

I'm working on some back-end code Take a look at the code snippet below [HttpGet] public ActionResult GetQuestions() { var _id = TempData["ID"]; var questBlock = db.QuestionBlocks .Where(x => x.Interview_Id == ...

Is there a way to eliminate a tag that includes all attributes except for certain ones?

Here is the code I am working with: var str = `<p>paragraph<a>link</a></p> <div class="myclass"> <div>something</div> <div style="mystyle">something</div> ...

Is there a way to make $animate.removeClass function within a directive without needing to use $eval

I have developed a custom directive that smoothly fades out and fades in the content whenever there is a change in the model. app.controller('myCtrl', function($scope, $interval) { $scope.number = 0; $interval(function() { $scope.number+ ...

Vue and Moment JS facing a challenge with today's date validation

I am developing a VueJS application that includes a form component. Within this form, there is a field for selecting dates. My goal is to display an error message if the chosen date is older than today's date. Essentially, the selected date should ...

What is the best way to simulate our services for controller testing?

Currently delving into angular js and experimenting with testing a controller. Here is the service I am using: angular.module('test'){ service.getAllServices = function() { var fullPath = url var deferre ...

Developing a feature to organize content by categories and implement a functionality to load more data efficiently using NodeJS routes

I am looking to develop a system that limits the number of displayed posts and includes a "load more" button to retrieve additional posts from where the limit was previously reached. Additionally, I want to implement the functionality to change the orderin ...

What is the best way to incorporate parallax scrolling in the center of a webpage?

I am trying to implement a parallax scrolling effect in the middle of my page, but it seems to be causing issues once I reach that section while scrolling. I attempted to use intersection observer, but unfortunately, it did not resolve the problem. const ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

Bits of code and the internet

When it comes to displaying code on the web, there are a few key steps involved: Encoding HTML entities Formatting The most basic workflow would involve: Start with a code snippet like: <html> I'm a full page html snippet <html>. ...

What steps should I follow to update this React Navigation v5 code to v6?

As I delve into my studies on React Native, I came across the deprecation of the tabBarOptions feature. I understand that now we need to include it in screenOptions, but I'm facing issues with implementing this in my code. I tried enclosing them in br ...

The styling of the close button in Ngb-bootstrap alerts is not being implemented correctly

In the midst of my Angular project, I implemented the ngb-alert to display alerts. Initially, everything was running smoothly with my alert. However, upon upgrading my Angular version and all related dependencies to the most recent versions, I observed tha ...

Is there a way to eliminate the quotes from the JavaScript output?

I've gathered data in the following format: [ 0: {latitude: "0", longitude: "0", user_country_name: "-", user_country_code: "-", total_visitors: 4} 1: {latitude: "-33.867851", longitude: "151.20 ...

Determine the number of elements in an array that are equivalent to the Boolean value of

After going through several discussions on this topic, I seem to be struggling with the concept. I have an array of objects with different properties and values. My goal is to count a specific property in the array only if its value is true. In the JSON d ...

Node.js and Express constantly face the challenge of Mongoose connecting and disconnecting abruptly

I have been running an Express (Node.js) app connected to MongoDB using Mongoose for a while now. Everything was working smoothly until recently, when it started acting up. It appears that the server is establishing a connection with MongoDB only to disco ...

Which event in the listbox should I trigger to adjust the scroll position?

My webpage includes a listbox inside an update panel. I've managed to capture the scroll position, but now I'm facing difficulty in identifying the right javascript event to call my function for setting the scroll position after the update panel ...

D3.js: Exploring the beauty of layered legends

I have a question regarding creating legends with triangle shapes. Specifically, I am trying to create two triangles representing "Yes" and "No". However, when I run the code below, the triangles end up overlapping each other. In an attempt to separate t ...

Can we retrieve props that have not been explicitly passed down?

How can I access the prop "showPopover" from the constructor or another method? This prop was originally created in a separate component and now that I've integrated it into this component, I'm looking for a way to easily retrieve and modify it. ...