Looking to send the node object generated in a loop to the edges

Currently, I am facing some challenges while reading a JSON file and looping through it to generate a graph with nodes and edges using the JavaScript library cytoscape. I have encountered some issues as a beginner in this process. Below is my pseudo code with some pseudo bugs.

1) Create a new node for each node labeled 'x'.

2) For each edge in the list of edges, create an edge with 'source' and 'target'.

The problem arises when creating the edge because it requires passing each node object as an argument (sourceNode, targetNode, {weight: 'y'}). Therefore, the following approach will not work:

var edge = graph.newEdge({source: graphP.elements.edges[j].data.source},
                          {target: graphP.elements.edges[j].data.target});

I attempted to resolve this by creating an array and storing each new node in it. However, I found that I was overwriting the variable name value and ending up with an array of length 1. Although all the nodes are created, I need a way to access them again in order to create the edges without pointing to themselves.

I believe I may need to use something like nodeObject.hasKey[label] to match and retrieve the node ID based on the label, then proceed with creating new edges?

I seem to have gotten myself tangled in confusion here. Any advice on how to untangle this situation would be greatly appreciated. The code snippet below includes the current code along with an abbreviated JSON file.

<html>
<head>
  <title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>

<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>-->

<script/>  
$(document).ready(function(){
  $.ajax({
    url: 'https://rawgit.com/theresajbecker/CompBio/master/SuperSmallNodes.json',
    type: 'GET',
    dataType: 'json'
  }).done(function(graphP) {  

    console.log(graphP);

    var graph = new Springy.Graph();

    for ( i = 0  ; i < graphP.elements.nodes.length ; i++ ) { 
        var nodeArray = []
        var Nlabel1 =  graphP.elements.nodes[i].data.label
        var Nlabel2 =  graphP.elements.nodes[i++].data.label
        console.log('Nlabel1')
        console.log(Nlabel1)
        console.log('Nlabel2')
        console.log(Nlabel2)
        var NN1 = graph.newNode({label: Nlabel1})
        var NN2 = graph.newNode({label: Nlabel2})
        nodeArray.push(NN1)
        nodeArray.push(NN2)
        graph.newEdge(NN1,NN2, {weight: .5})

                                                 }
    console.log('NODE ARRAY')
    console.log(nodeArray)  

        console.log('WINDOW')
jQuery(function(){
  var springy = window.springy = jQuery('#springydemo').springy({
    graph: graph,
    nodeSelected: function(node){
      console.log('Node selected: ' + JSON.stringify(node.data));
    }
  });
});

    });  


});
</script>
    <div>
<canvas id="springydemo" width="800" height="400" style="border: 1px solid black;"></canvas>
</div>


</body>
</html>

Answer №1

To optimize the code, it would be beneficial to declare nodeArray outside of the loop:

let nodeArray = []
for (let i = 0; i < graphP.elements.nodes.length; i++) { 

By doing so, you can prevent unnecessary re-initialization in each iteration which was causing a length of 1.

Answer №2

After encountering some distractions, I realized that my array initialization was happening inside the loop - a rookie mistake on my part. Nevertheless, here is how I successfully managed to send the sourceNode and targetNode objects to the newEdge function.

<html>
<head>
  <title>Example using Springy.js for node demonstration</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>

<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>-->

<script/>  
$(document).ready(function(){
  $.ajax({
    url: 'https://rawgit.com/theresajbecker/CompBio/master/SuperSmallNodes.json',
    type: 'GET',
    dataType: 'json'
  }).done(function(graphData) {  

    console.log(graphData);


    var graph = new Springy.Graph();
    var nodesArray = []

    for ( j = 0  ; j < graphData.elements.nodes.length ; j++ ) { 
        var Nlabel2 =  graphData.elements.nodes[j].data.label
        var Nmass2 =  graphData.elements.nodes[j].data.mass

        var NN2 = graph.newNode({label: Nlabel2}, {'text-outline-width': Nmass2});
        nodesArray.push(NN2)
        }
        console.log(nodesArray)

        function findNodeByLabel(arr, value) {
          for (var m=0; m < nodesArray.length; m++) {
            if (arr[m].data.label == value) {
            console.log("The corresponding element object should be below")
            return arr[m];
            }
          }
        }


        function getSourceAndTargetNodes(graphData) {
          for (var t=0; t < graphData.elements.edges.length; t++) {
            var getSource2 = graphData.elements.edges[t].data.source
            var getTarget2 = graphData.elements.edges[t].data.target
            graph.newEdge(findNodeByLabel(nodesArray, getSource2),findNodeByLabel(nodesArray, getTarget2));

        }
        }

    getSourceAndTargetNodes(graphData)


        console.log('WINDOW')
jQuery(function(){
  var springy = window.springy = jQuery('#springydemo').springy({
    graph: graph,
    nodeSelected: function(node){
      console.log('Node selected: ' + JSON.stringify(node.data));
    }
  });
}); 

    });  


});
</script>
    <div>
<canvas id="springydemo" width="800" height="400" style="border: 1px solid black;"></canvas>
</div>


</body>
</html>

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

Combine bar and stacked bar charts on a single graph with morris.js

Can a combination of a stacked bar chart and a regular bar chart be created in morris.js? I have successfully generated a stacked bar chart using the following code: Morris.Bar({ element: 'bar-example', data: [ {x: '2011 Q1', ...

My regular expression is not working for searching IP addresses on the server. What

I'm currently working on a challenge to identify valid IPv4 addresses in dot-decimal format. The goal is to write an algorithm that will determine if the IP addresses consist of four octets, with values ranging from 0 to 255, inclusive, while also ens ...

What is the best way to link a dynamic property with a bootstrap popover within a nested v-for loop?

After spending several days searching for an example to guide me without success, I am turning to SO with my specific use case. I am currently working on a Bootstrap Vue layout where I need to load dates into 12 buttons corresponding to months and display ...

Utilizing a JQuery variable as an OFFSET parameter in an SQL query

Currently, I am working on incorporating infinite scroll functionality for posts within a news feed. The idea is for the posts to be dynamically loaded into the news feed when the user reaches the footer. The Challenge I am facing an issue with inc ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

Enhancing ChoicePrompt with ListStyle.heroCard: Adding Personalized Data

I have developed a custom ChoicePrompt with the unique style of ListStyle.heroCard: import {ChoicePrompt, ListStyle} from 'botbuilder-dialogs'; import {PromptValidator} from 'botbuilder-dialogs/src/prompts/prompt'; import {FoundChoice} ...

Personalized HTML ProgressBar featuring indicators

As I explore options for creating a progress bar/timeline with the ability to add markings (white lines shown in the image below) upon clicking a button, I've looked into HTML5 canvas and custom jQuery solutions. I'm curious if anyone has any spe ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

``How can I effectively handle and display Angular JSON text in an alert message?

Is there a way to pass a JSON entry into the onClick event for triggering an alert box in AngularJS? I'm attempting to display a message box with the content of a specific JSON entry when clicking on a row within a table. The issue seems to be isolat ...

Trouble with Mongoose: Data Not Being Saved

I'm encountering difficulties with a basic query on my database. While following this tutorial at https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4, the author receives a JSON object containing the name field (the only custom fi ...

Sending a JSON file to a PHP script

I need help passing a JSON file to PHP using jQuery. When I check the response, I receive an error stating "json_decode expects parameter 1 to be a string." Below is my jQuery routine: $("#ProcessData").click(function(){ var cols = $("#tblGroup thead t ...

Discovering common time intervals without the date component in between

I need to identify the intersection between two time ranges, focusing solely on the time and not the date. For instance, range_1 is from 9AM to 6PM while range_2 spans from 5PM to 8AM. The times are in the 24-hour format. I have a solution that finds the o ...

Validating Responses in RESTful APIs

As I work on creating a RESTful API, I find myself pondering the ideal format for validation error messages. Take, for instance, my account creation endpoint which accepts a JSON object: user: { first_name: string, last_name: string, address: { ...

What is the best method for combining JSON files using jq?

Can anyone offer advice on how to concatenate around 50 JSON files using jq? The JSON files have a structure like this: file-1.json { "name": "john" } file-2.json { "name": "Xiaoming" } I aim to create a single file file-all.json That should lo ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

What could be the reason behind the infinite digestion loop triggered by my custom filter?

I devised a personalized filter that segregates an array of key-value pairs into an object based on grouping values by the first letter of a specific property. For instance Input: [{foo: 'bar'}, {faz: 'baz'}, {boo: 'foo'}] O ...

What is the best way to add a collection of JSON strings to a dictionary array?

I have an array containing JSON strings and I would like to convert the entire array into a dictionary. I am familiar with converting individual JSON strings into dictionaries, but is it possible to convert the entire list at once? Here is an example of my ...

Transforming JSON data into a pandas dataframe using Python

I am looking to merge multiple JSON files into a single dataframe. Here is an example of the JSON object: {'alerts': [{'affected_services': {'elevators': [], 'services': [{'m ...

What is the best way to utilize a basic jQuery hide/show function to display everything before hiding it?

I have a dropdown menu where selecting an option will display a specific section based on the matching value and class, while hiding all other sections. How can I set it up so that before any selection is made, all sections are displayed and only hide afte ...

Deliver Compressed Files following Angular CLI --Prod Configuration

After using the Angular CLI's command to minify my basic Angular app, a dist folder was generated with the project folder and minified files. However, when I run ng serve, it always serves the unminified development files, whether it's in the roo ...