Exploring JSON Data with D3 through Dynamic Jumps

I'm currently delving into the realm of D3 visualization and I have a feeling that there might be a solution out there for what I'm attempting to achieve.

Let's assume I have JSON data structured like this:

var arr = [
    {
        "name":"John",
        "maxAge": 35,
        "info":[
            {
                "age":31,
                "height":6,
                "weight":155,
                "eyes":"green"
            },
            {
                "age":35,
                "height":6,
                "weight":165,
                "eyes":"green"
            }
        ]
    },
    {
        "name":"Eric",
        "maxAge":30,
        "info":[
            {
                "age":29,
                "height":5,
                "weight":135,
                "eyes":"brown"
            },
            {
                "age":30,
                "height":5,
                "weight":155,
                "eyes":"brown"
            }
        ]
    }
]

Imagine I'm iterating through the data using something akin to the following:

var outerDiv = d3.select("body")
    .selectAll("div")
    .data(arr)
    .enter()
    .append("div")
    .attr("class","outerDiv");

to create outer divs for John and Eric, followed by:

var innerDivs = outerDiv.selectAll("p")
    .data((d) => arr.info)
    .enter()
    .append("p")
    .html("Weight = " + info.weight)
    .attr("class","outerDiv");

to iterate through each piece of 'info' and represent it visually. Nonetheless, my visualization calls for me to 1) access 'maxAge' while looping through the 'info' array and 2) access 'info[1].height' when within 'info[0]'. Can either of these scenarios be accomplished?

Answer №1

Yes, you can achieve both of your requirements. Utilize the d3Selection.each method for this purpose.

Check out this example below:

var data = [
    {
        "name":"John",
        "maxAge": 35,
        "info":[
            {
                "age":31,
                "height":6,
                "weight":155,
                "eyes":"green"
            },
            {
                "age":35,
                "height":6,
                "weight":165,
                "eyes":"green"
            }
        ]
    },
    {
        "name":"Eric",
        "maxAge":30,
        "info":[
            {
                "age":29,
                "height":5,
                "weight":135,
                "eyes":"brown"
            },
            {
                "age":30,
                "height":5,
                "weight":155,
                "eyes":"brown"
            }
        ]
    }
]

var outerDiv = d3.select("body")
    .selectAll("div")
    .data(data)
    .enter()
    .append("div")
    .attr("class","outerDiv");

var innerDivs;

outerDiv.each(function(d){
  innerDivs = d3.select(this)
    .selectAll("p")
    .data(d.info)
    .enter()
    .append("p")
    .html(function(info,i){    
      var nextInfo = d.info[i+1];    
      if(nextInfo) console.log(JSON.stringify(nextInfo));
      return "Weight = " +info.weight +", MaxAge: "+d.maxAge;
     })
    .attr("class","innerDiv");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

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

Can a callout or indicator be created when a table breaks across columns or pages?

As we develop HTML pages for printing purposes, one specific requirement for tables is to include an indicator like "Continues..." below the table whenever a page or column break occurs. Additionally, in the header of the continuation of the table, we need ...

Error: React-Redux/Jest Invariant Violation - The "store" could not be located

I have a test file set up that is similar to the one used by create-react-app. Here is my App.test.js file: App.test.js import React from 'react'; import ReactDOM from 'react-dom'; import { App } from './App'; it('rend ...

Creating multiple countdowns in AngularJS using ng-repeat is a handy feature to have

Currently, I have a small AngularJS application that is designed to search for users and display their upcoming meetings. The data is retrieved from the server in JSON format, with time displayed in UTC for easier calculation to local times. While I have s ...

Creating a reusable Angular directive that encapsulates a jQuery lightbox functionality

Currently, I am attempting to integrate a customized jquery lightbox within an Angular directive. My goal is to create the directive in such a way that it simplifies the usage of the lightbox without modifying the original jquery code, as it is also used i ...

What makes (_=1)=>$=>_++ act as a tally?

One of my buddies encountered this question during a JavaScript job interview: Can you explain how this counter functions? In other words, what does the non-minified version look like? let Counter = (_=1)=>$=>_++ let c1 = Counter() co ...

unable to toggle the navbar

Currently, I am facing an issue with the navbar-toggle button while using Bootstrap. Initially, I thought the problem was with my navbar code, so I tried pasting the example from the Bootstrap Website, but it did not work either. The button appears, but t ...

Creating a nested array within a JavaScript object using JavaScript/nodejs dynamically

I am faced with an array of JavaScript objects structured as follows: const source = [ { title: 'Expanse', season: 1, episode: 1, path: 'download.mkv' } , { title: 'Expanse', season: 1, episode: 2, path: 'download.m ...

Choosing different elements using identical classes in JQuery

Struggling with a coding problem that seems like it should be an easy fix, but can't quite figure it out. The HTML code I have is as follows: <section class="actualite"> <div class="actualite-text"> <h3 class="title"&g ...

Retrieving DataFrame from nested, labeled arrays using Spark

Currently, I am utilizing Spark to parse JSON documents that have the following structure: { "items": [ {"type": "foo", value: 1}, {"type": "bar", value: 2} ] } In this format, the el ...

AngularJS - Implementing toggle functionality for checkbox on button click

Here's my situation: I have a group of checkboxes that are initially disabled. When button 1 is clicked, I want the checkboxes to become enabled and buttons 2 & 3 to appear while hiding button 1. If buttons 2 or 3 are clicked, I want to disable the c ...

Issue with sending data from JQuery Ajax to PHP codeExplanation:The problem

Here is the output from myscript.js: [{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}] This is the content of myscript.js: if (addList.length) { $.ajax($.extend({}, ajax ...

Rails is generating unexpected JSON responses when used with Objective-C's NSArray

I've been developing an API using Rails and Objective-C. On the Objective-C side: NSLog(@"NSArray: %@", allPosts); It seems like there might be an issue on my Rails side. I was expecting a response like this: { id: 1, galleries: [ ...

List component in Angular not refreshing after sorting the array in the service

Currently, I am delving into the realm of Angular (version 5+) to enhance my skills by working on a small project. The project involves setting up basic routing functionalities to showcase the ContactList component upon selecting a navigation tab. Addition ...

Animate out Material UI element with zoom effect and then remove it from the

I'm currently working on a dynamic user interface that allows for adding and removing items dynamically. Each item has both an add and remove button, with a special animation effect using Zoom. While this works smoothly when adding new items, I encoun ...

Is the integration of async prior to the created method in Vue disrupting the lifecycle?

Is it advisable to include async before the created method in Vue.js? Won't this disrupt the Vue life cycle since using async makes it an asynchronous action that gets sent to the background queue, potentially allowing methods like mounted to execute ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Is there a chart component in bootstrap that allows for customization of time frames?

You can find this image in the search results when looking for rates online I'm interested in creating a similar chart, but I'm not sure what it's called. Can I use bootstrap line charts to create something like this? ...

After a certain time has passed, an event will occur once a div element has been assigned

Is there a way to show div2 only after div1 has been given the '.selected' class for a set duration, and then hide it again when div1 loses the '.selected' class? What would be the most efficient approach to achieve this? ...

What are the implications of AngularJS's filter on performance?

I came across an interesting article on optimizing ng-repeat in AngularJS that discussed the following: An AngularJS filter in your HTML will run multiple times during every digest cycle, even if there have been no changes in the data or conditions. Thi ...

Utilizing jQuery to scrape HTML and dynamically manipulate elements

Is there a way to retrieve HTML content from a different subdomain and incorporate it into the current site? HTML snippet: <head> <body> <div id = "items"> <div id = "#one"> <ul> <li><a href = "#">C ...