Can someone provide guidance on iterating through a nested array in d3 and appending child elements accordingly?

Looking at my JSON data, here is an example of what it contains.

var data = [ 
 { animal: 'dog', names: [ 'mark', 'cooper', 'pooch' ] },
 { animal: 'cat', names: [ 'mary', 'kitty' ]
];

Now, I want to use d3 to create SVG elements based on this data in a specific format.

<svg id="mysvg" width="500" height="500">
 <g data-animal="dog" transform="translate(0,0)">
  <text x="10" y="10" fill="black">dog</text>
  <text x="10" y="25" fill="black">mark</text>
  <text x="10" y="40" fill="black">cooper</text>
  <text x="10" y="55" fill="black">pooch</text>
 </g>
 <g data-animal="cat" transform="translate(0, 100)">
  <text x="10" y="10" fill="black">cat</text>
  <text x="10" y="25" fill="black">mary</text>
  <text x="10" y="40" fill="black">kitty</text>
 </g>
</svg>

To start creating the g element, I usually follow this process. The g variable helps me in appending more elements later.

var g = d3.select('#mysvg')
 .selectAll('g')
 .data(data)
 .enter().append('g')
 .attr({ 
  'data-animal': function(d) { return d.animal; }, 
  transform: function(d) { return 'translate(' + ... + ')'; } 
 });

Once the g is set up, I can add the first text element using the following steps.

g.append('text')
 .attr({ x: '10', y: '10', fill: 'black' })
 .text(function(d) { return d.animal; });

However, to append more elements to each g by iterating over the array data[i].names, how should I approach it?

Answer №1

To implement this method, you can leverage the .each function to iterate over each data point. It's important to note that we utilize d3.select(this) to access the current g element.

 g.each(function(d) {
    for(var j = 0; j < d.names.length; j++) {
     d3.select(this).append('text')
       .attr({ x: '10', y: '10', fill: 'black' })
       .text(function(d) { return d.names[j]; });
  }
 });

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 can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

Changing an array in JavaScript to suit different needs

Here is an example of a JSON array: [ {category: 'Category 1', data: [ {date: '01/04/2021', value: 10}, {date: '01/03/2021', value: 20}, {date: '01/02/2021', value: 5}] }, {category: 'Category 2' ...

Tips for ensuring that the lightbox scrolling feature only affects the lightbox and not the entire page

Currently, I am utilizing the lightbox_me jQuery plugin to trigger a lightbox when a user clicks on a product. The issue I am facing is that the lightbox content often extends below the visible area, causing the entire page to scroll when using the right s ...

There is an issue with loading Google Maps on ASP.NET

My C# Web Application (asp.net web-forms) has a peculiar issue within the Default.aspx page that is part of a Master Page. The google map embedded within the content flickers once but never fully loads. Surprisingly, when I transfer the exact code from Con ...

Bootstrap form toggle switch component for ReactJS

I'm having trouble figuring out why the default value for my react-bootstrap switch won't set to false (off). It seems like the only way it changes is when I trigger the onChange event handler. Am I overlooking something? Below is the section of ...

Implement a mandatory route in Express

Is it possible to enforce a specific route? Scenario: Consider the following route A: notiSchema = notification model router.get('/set', function(req, res){ User.findById("userId", function(err, foundUser){ foundUser.notiSchemaSen ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...

The Javascript alert function always seems to fail to trigger

Below is the complete code I am working with: if( javascript.isGarbage() != true) { alert('I am not garbage!'); } Can someone please explain why this code does not produce an alert message??? ...

Tips for Utilizing jQuery each Loop

I am attempting to create a foreach loop that will iterate through hidden values on the page, compare them with an external API using Ajax, and display the API results in a < ul > for example. Sample model ITEM1 metavalue (which needs to be che ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

How to access a specific key in a JSON string using square brackets in PHP

My current challenge involves dealing with an array: [{"title":" \ud83c\uddfa\ud83c\udde6 \u041b\u0443\u0447\u0448\u0435\u0435 \u043a\u0430\u0437\u0438\u043d\u04 ...

Specify the minimum required spacing between two meshes in THREE.JS

I'm working on a code that generates clouds with random positions, rotations, and scales. However, sometimes these clouds can end up clipping together when they are generated close to each other or near another object. I want to set a minimum distance ...

How can I read "binary" characters from a file using JavaScript?

When I mention binary, I'm referring to ghjkl54╞←‼╝454┴ rather than 10101110. I am interested in implementing a tilemap loading functionality in JavaScript without having to redo my map editor, which is coded in Java and exports maps as bin ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Detecting when an object exits the proximity of another object in ThreeJS

In my ThreeJS project, I have planes (Object3D) flying inside a sphere (Mesh). My goal is to detect when a plane collides with the border of the sphere so that I can remove it and respawn it in a different location within the sphere. I am wondering how I ...

Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungaria ...

Can a default arrow function be exported in TypeScript using only one line?

const myFunction: () => void = () => { console.log('I am able to export my function like this'); }; export default myFunction; export default () => void = () => { console.log('I am unable to export my function like thi ...

typescript api overlooking the async await functionality

My controller contains an asynchronous method that is supposed to set a results object. However, I'm facing an issue where instead of waiting for the 'await' to finish executing, the code jumps to the response object call prematurely, leavin ...

Attempting to open and display the contents of a text file (.txt) within a modal dialog box upon clicking a button

I am attempting to develop a modal that will appear when the user clicks on a specific button. The goal is for this modal to showcase text retrieved from a separate file stored on the server. My aim is to show this text within a dialog box modal. So far, ...