Error: Trying to add an element to an undefined variable (d3 force layout)

I've been racking my brain trying to solve this error I keep encountering while working with a force layout. The problem arose when I switched to reading nodes from a JSON file. When I comment out certain lines, the error disappears. But if I leave them as they are, I receive a "Cannot call method 'push' of undefined" message. It's baffling me and I can't seem to pinpoint the issue. Is there something obvious that I'm overlooking?

<html>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<script>

   d3.json("http://katejustin.com/autosys1.json", function(data) {

   //var nodes = {};

   //data.links.forEach(function(link) {
   //   link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
   //   link.target = nodes[link.target] || (nodes[link.target] = {name: link.target}); });


var width = 200,
    height = 200;

var svg = d3.select("body").append("svg:svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    //.nodes(d3.values(nodes))
    .nodes(data.nodes)
    .links(data.links)
    .size([width, height])
    .distance(100)
    .charge(-1000)
    .start();
});
</script>
</html>

Answer №1

One issue arises when trying to access nodes using the name property in links, as opposed to the original method of accessing nodes by index.

In such cases, I often resort to a simple trick that may not be the most elegant solution but gets the job done:

var findNode = function(id) {
    for (var i in force.nodes()) {
        if (force.nodes()[i]["name"] == id) return force.nodes()[i]
    };
    return null;
}

var pushLink = function (link) {
    //console.log(link)
    if(findNode(link.source)!= null && findNode(link.target)!= null) {        
        force.links().push ({
            "source":findNode(link.source),
            "target":findNode(link.target)
        })
    }
}

var force = d3.layout.force()
    .nodes(data.nodes)
    .size([width, height])
    .distance(100)
    .charge(-1000)
    .start();

data.links.forEach(pushLink)

Essentially, these functions aim to update each link's source and target with the actual node object from force.nodes.

You can view a working example on jsFiddle here: http://jsfiddle.net/chrisJamesC/nrbQ4/1/ (Output is visible through console logs as visualization is not provided).

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

Press the button using Selenium WebDriver with Java

Currently, I am utilizing Selenium Webdriver for Chrome and Firefox along with Java. After performing various actions, I stumbled upon a typical source code snippet like this: <input type="button" value="yoyo" class="btn" onClick="SubmitForm(this, &ap ...

Which hook should be implemented for automatically updating stock levels after a successful payment on WooCommerce?

When working with WooCommerce, I have implemented my own custom payment method using javascript code. I have successfully retrieved the total amount and passed it to my payment system using the following PHP code: <?php $GLOBALS['cart_total'] ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

Which is the better option for selecting DOM elements in a Vuejs 3 application: using raw js or jquery?

 I am currently working on developing an application using Node.js and Vue.js 3. One of the features I have implemented is a sidebar that dynamically fetches links from a routes file and displays them. The sidebar consists of a component that organize ...

Creating a specific type of table using Ruby on Rails

Is it feasible to create a table with two columns, where the left column incorporates multiple rows with a scroll bar, and the right column contains a large box housing buttons that alter based on the selection of blocks in the left column? ...

Validation method in jQuery for a set of checkboxes with distinct identifiers

I am faced with a situation where I have a set of checkboxes that, due to the integration with another platform, must have individual names even though they are all interconnected. <div class="form-group col-xs-6 checkbox-group"> <label cla ...

How can I make my navbar stay fixed in place and also activate the transform scale functionality?

After fixing the position of my navbar with the class "top," I noticed that the transform property scale does not work on the div element I applied. The hover effect on the box only works when I remove the position from the navbar. This is the HTML code: ...

Is there a way to trigger this pop-up after reaching a certain percentage of the page while scrolling?

I've been working on a WordPress site that features an "article box" which suggests another article to users after they scroll to a certain point on the page. However, the issue is that this point is not relative but absolute. This means that the box ...

What could be causing the asynchronous function to return a pending promise even after using the await keyword?

I seem to be overlooking something as I cannot comprehend why my promise does not resolve. I have simplified the code to this basic example: ... console.log("before"); const promise = second(); console.log("after"); console.l ...

Utilize an asynchronous method to upload files to Google Cloud Storage in a loop

I am new to using Javascript and have been working on a loop to upload images to Google Cloud Storage. While the image uploads correctly with this code, I'm facing an issue where the path (URL) is not being saved in the database AFTER the upload. I a ...

I am unsure about implementing the life cycle in Svelte.js

Unknown Territory I am not well-versed in front-end development. Desire to Achieve I aim to utilize the lifecycle method with SvelteJS. Error Alert An error has occurred and the lifecycle method is inaccessible: ERROR in ./node_modules/svelte/index.m ...

I lose my user interface after a series of clicking events

I've created a React application that generates new quotes without repetition, but I'm encountering an issue where the UI disappears after clicking enough times. What could be causing this behavior in my code? The console displays an object error ...

Datepicker malfunction in Django's administrative interface

Currently, I am attempting to filter results by dates using daterangefilter. However, I am experiencing issues with my datepicker functionality. Although the icon appears, the datepicker itself is not functioning as expected. In an effort to troubleshoot ...

Issues with clickable links within a table cell

I am facing an issue with a table where rows <tr> are generated dynamically by a PHP loop. I have transformed the entire row into a link, but the problem arises when there is an <input type="checkbox"> within the row. Whenever I check the check ...

Ways to reach component method via router

When making an Ajax request and displaying the data in a table component, I encounter an issue where I need to extract the clicked data for use in another Ajax request within a different component that is called through React-Router. The challenge lies in ...

AngularJS Enhanced Multi-Level Table

Currently, I'm attempting to display 3 tables on a single page that pull data from the same array but filter it using ng-repeat. I followed a similar table format from another source and you can view my JS Fiddle Link here: http://jsfiddle.net/6Texj/1 ...

What is the best method for transforming a nested object into an array of objects?

This object contains nested data var arr = [{ "children": [{ "children": [{ "children": [], "Id": 1, "Name": "A", "Image": "http://imgUrl" }], "Id": 2 "Name": "B", ...

CSS Testimonial Slider - Customer Feedback Display

I'm having some issues with the code below: <div id="box"> <div class="wrapper"> <div class="testimonial-container" id="testimonial-container"> <div id="testimon ...

Encountering an error message stating "Please enable JavaScript to run this application" when making React API calls after deploying a ReactJs app on the Firebase server

I'm currently working on a React JS app that calls various APIs. The backend of this application is a NodeJs server deployed in GCloud. While everything runs smoothly when I test the React app locally, I encountered an issue after deploying it to Fir ...

Utilizing OrientDB in a SailsJS Application: A Step-by-Step Guide

I'm diving into the world of NodeJS and SailsJS after working with Rails and PHP. I'm interested in integrating SailsJS with OrientDB, but I'm unsure of the best approach to take. I've come across two options so far, but the available ...