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>