Error in D3: The property "age" is not defined

Currently, I am in the process of developing a force-directed graph using D3 for visualization. One of the challenges I encountered was implementing an age filter utilizing radio buttons on my HTML page and incorporating data from an imported JSON file.

The desired outcome is to have nodes within a specified age range (derived from the JSON data) become highlighted when a user selects a radio button. However, I kept encountering an error message that read "Uncaught TypeError: Cannot read property 'age' of undefined" whenever any of the radio buttons were clicked. Despite reviewing my code multiple times, I couldn't pinpoint the exact issue. The error seems to originate from this line of code: "if(d.age >= ageBracket[0] && d.age <= ageBracket[1])". Perhaps I need to implement another loop for 'd.age'?

**Update: I have included additional snippets of both my JavaScript and HTML code below.

JavaScript Code:

function createGraph() {

// Rest of the JavaScript code here...

});

}

HTML Code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>D3 Visualization - Force Directed Graph</title>

    // Remaining HTML code here...

  </body>
</html>

A snippet from the JSON file:

"nodes":[
{ "id": "1", "name": "John", "age": "31", "gender": "M"},
{ "id": "2", "name": "Emily", "age": "23", "gender": "F" },
{ "id": "3", "name": "Crystal", "age": "23", "gender": "F" },
{ "id": "4", "name": "Himiko", "age": "23", "gender": "F" }],
"links": [
{ "source": "hospital1", "target": "1", "value": 200 },
{ "source": "hospital2", "target": "2", "value": 200 },
{ "source": "hospital3", "target": "3", "value": 200 },
{ "source": "hospital4", "target": "4", "value": 200 }]

Answer №1

After some debugging, it became clear that the issue with your code stemmed from treating the array holding your data as the nodes themselves. The solution involved correctly selecting the SVG 'nodes' and 'links' you had created in the 'createGraph' function. Take a look at this updated codepen: https://codepen.io/anon/pen/wxMmvm?editors=0011

To address this issue, I specifically targeted the 'nodes' and 'links' and utilized the '.each' method to execute a function on each of these elements for age range validation:

//Code for radio button filter on age range
d3.selectAll("input[name=radiob]").on("change", function(d) {
  var self = this;
  var ageBracket = {
    min : self.value.split('-')[0],
    max : self.value.split('-')[1]
  };

  d3.selectAll('.nodes')
    .selectAll('circle')
    .each(function (d) { 
      if (d.age >= ageBracket.min && d.age <= ageBracket.max) {
        d3.select(this).style('opacity', 1)
      } else {
        d3.select(this).style('opacity', 0.2)
      }
    })

  d3.selectAll('.links')
    .selectAll('line')
    .each(function (d) { 
      if (d.target.age >= ageBracket.min && d.target.age <= ageBracket.max) {
        d3.select(this).style('opacity', 1)
      } else {
        d3.select(this).style('opacity', 0.2)
      }
    })
});

Important Notes:

  • The loop found within the function managing the radio button change event seemed unnecessary, so I removed it.
  • Since the JSON data provided wasn't functional, data from this bl.ock: https://bl.ocks.org/mbostock/4062045 was used instead. Subsequently, age/gender-related data was incorporated but may need modification based on your requirements.
  • I adjusted the radiobutton values and introduced another option 'Any' to align with my ageBracket retrieval code. Refer to the HTML structure in the linked codepen above for details.

Answer №2

After introducing a few Hospital entries into the json document

{
"nodes":[

    { "id": "1", "name": "John", "age": "31", "gender": "M"},
    { "id": "2", "name": "Emily", "age": "23", "gender": "F" },
    { "id": "3", "name": "Crystal", "age": "23", "gender": "F" },
    { "id": "4", "name": "Himiko", "age": "23", "gender": "F" },

    { "id": "hospital1", "name": "H1", "age": "31", "gender": "M"},
    { "id": "hospital2", "name": "H2", "age": "23", "gender": "F" },
    { "id": "hospital3", "name": "H3", "age": "23", "gender": "F" },
    { "id": "hospital4", "name": "H4", "age": "23", "gender": "F" }
],

   "links": [
    { "source": "hospital1", "target": "1", "value": 200 },
    { "source": "hospital2", "target": "2", "value": 200 },
    { "source": "hospital3", "target": "3", "value": 200 },
    { "source": "hospital4", "target": "4", "value": 200 }]
}

The system successfully displayed the nodes and connections.

However, upon selecting radio buttons, an error occurred when trying to access fields from d. The radio button change callback function lacked proper arguments. To enable age comparison, it was necessary to create an age comparison function to adjust the visibility of both nodes and links accordingly.

    d3.selectAll("input[name=radiob]").on("change", function () {
        var age = document.getElementsByName("radiob");
        var ageBracket;
        node.style("opacity", 1);
        link.style("opacity", 1);
        for(var i=0; i < age.length; i++) {
            if(age[i].checked) {
                ageBracket = age[i].value.split("-");
                var testAgeBracket = function (d) { return (d >= ageBracket[0] && d <= ageBracket[1]) };
                node.filter(function(d) { return testAgeBracket(d.age); })
                .style("opacity", "0.2");

                link.filter(function(d) {
                    return !testAgeBracket(d.source.age) &&
                           !testAgeBracket(d.target.age); })
                .style("opacity", "0.2");

                link.filter(function(d) {
                    return testAgeBracket(d.source.age) ||
                           testAgeBracket(d.target.age); })
                .style("opacity", "1"); 
            }
        }
    });

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

Transforming an array from two dimensions to one dimension using PHP

Here is an example of an array: array(1) { ["foo"]=> array(2) { [1]=> string(5) "abcde" [2]=> string(4) "pqrs" } } Now, I would like to transform it into the following format: array(2) { [1]=> string(5) "abcde" [ ...

Inquiries for Web-Based Applications

As I contemplate coding my very first webapp, I must admit that my skills are somewhere between beginner and intermediate in html, css, js, jquery, node, sql, and mongodb. However, the challenge lies in not knowing how to bring my vision to life. My ulti ...

The ng-model directive in drop-down selection elements

I have a series of questions along with their answers, and I want the user to select an answer from a drop-down menu. How can I achieve this? I've attempted the following code, but the select option isn't appearing on the screen. HTML: <div ...

How Python Flask sends a string as &#34 to an HTML page

I am working on a Flask app and I need to send simple JSON data from the app.py file to an HTML page. Here is the relevant code in my app.py: jsonArr = [{"type": "circle", "label": "New York"}, {"type": "circle", "label": "New York"}] return ...

Displaying specific data points

I am encountering an issue where I want to select multiple values and have each selected value displayed. However, when I make a selection, I only see one value from a single box. I do not wish to use append because it keeps adding onto the existing valu ...

Listening for dates in NodeJS and triggering callbacks

Is there a method or module available that allows me to monitor the date and trigger a specific action when a certain condition is met without relying on setTimeOut? What I am looking for: if(currentHour==="08:00:00"){ doJob() } EDIT : To clarify, wha ...

Converting an Array of Objects to a JSON string using JQuery

Consider the following variables: SymbologyObject and ValuesArray: var SymbologyObject = {}; var ValuesArray = []; You can fill them like this: var ValueOfField = "tree"; ValuesArray[ValueOfField] = []; var localStyle = {}; localStyle.fill = "#ffff"; l ...

The html carousel displays stacked images instead of scrolling

I have been staring at this code for what feels like an eternity, trying to figure out why it's only displaying stacked pictures instead of a functioning carousel. Perhaps I overlooked something crucial. Could someone please lend a hand? My code is pr ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

The radio button is failing to store its value in the MySQL database

I am currently facing an issue with a form that is being updated by PHP to a MySQL database. The form contains two radio buttons: <input type="radio" name="show_on_website" value="Y" /> Yes <input type="radio" name="show_on_website" value="N" /&g ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

The event handling mechanism in React JS for elements coming into view

Can someone please guide me on implementing the inview event in React JS? I want to achieve something like this: <div inview={handleInView}></div> I specifically need to add it to the Footer section so I can dynamically load more news a ...

What is the process of creating a color range in Java?

I am looking for a way to input a 6-digit RGB-hex number and then be able to click on a button that will display the corresponding color name. Unfortunately, I have not been able to find a color library in Java that can provide me with the names of arbitra ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

Is it possible to conduct brain.js training sessions multiple times?

Is there a way to specifically train my neural network with new information without having to retrain the entire model, considering the potential performance costs associated with it? The neural network was created using brain.js. ...

Troubleshooting: AngularJS ng-repeat not rendering JSON data

I have successfully retrieved JSON data from a database using PDO in Angular. The data is being returned as expected when I encode it to JSON. However, I am facing an issue with displaying the data using ng-repeat in Angular. Although the div elements are ...

Send a variety of jQuery element selectors to a function

myFunc() is connected to the document scroll event, resulting in frequent calls. To optimize performance, I intend to store HTML selections in variables and then pass them to the function. However, upon running the code snippet below, an error appears in t ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

Creating a reactive "virtual" getter for a class in VueJS

There are two objects in my code, BlogPost and Comment, with the following structure: class Comment { constructor (blogId, text) { this.blogId = id this.text = text } } class BlogPost { constructor (id, text) { this.id = id this.te ...

What could be causing the custom Angular filter to not return the expected results?

I have been working on a custom filter called "occursToday" for an array of "event" objects. This filter is supposed to return events that have a startDate matching the current date. However, when I test the filter, no events are displayed despite expectin ...