I am reading in and looping through a json file to create a graph with nodes and edges using a JavaScript library cytoscape, but am having some newbie problems. Here is my pseudo code w/pseudo bugs.
1) Create new node for each node with label 'x'
2) For each edge in edges, create edge with 'source', 'target'.
The problem that I am having is that to create the edge I need to pass each node object as the argument, (sourceNode, targetNode, {weight: 'y'} so something like this will not work
var edge = graph.newEdge({source: graphP.elements.edges[j].data.source},
{target: graphP.elements.edges[j].data.target});
I tried creating an array and writing each new node to it, but I just end up over-writing the value of the variable name and end up with an array of length 1. While all my nodes are created, I need a way to go back and access the nodes in order to create the edges ( and obviously not have them point to themselves).
I am guessing it will be some sort of nodeObject.hasKey[label] and match on that label to retrieve node ID, then create new edge?
I've thought myself in a knot here. Any advice is appreciated. Below is my current code with abbreviated json file read in.
<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>
At minimum, I would think you'd want to initialize nodeArray outside of the loop:
As is, the re-initialization in each loop would explain the length of 1.