javascript - D3 force layout - linking nodes by name instead of index -


i attempting link d3 nodes id instead of index (the node id generated application).

here nodes:

"nodes": [     {       "id": "338",       "name": "test node one",       "url": "http://www.google.com"     },     {       "id": "340",       "name": "test node two",       "url": "http://www.yahoo.com"     },     {       "id": "341",       "name": "test node three",       "url": "http://www.stackoverflow.com"     },     {       "id": "342",       "name": "test node four",       "url": "http://www.reddit.com"     }   ] 

they linked index:

  "links": [     {       "source": 0,       "target": 0,       "value": "0"     },     {       "source": 0,       "target": 1,       "value": "0"     },     {       "source": 1,       "target": 2,       "value": "0"     },     {       "source": 3,       "target": 2,       "value": "0"     }   ] 

however, want link them "id":

  "links": [     {       "source": "338",       "target": "338",       "value": "0"     },     {       "source": "338",       "target": "340",       "value": "0"     },     {       "source": "340",       "target": "341",       "value": "0"     },     {       "source": "342",       "target": "341",       "value": "0"     }   ] 

i've attempted solution proposed here: https://groups.google.com/forum/#!msg/d3-js/lwuhbeeipz4/0kziojcyvhij

by adding following lines before calling force.nodes:

  // make links reference nodes directly particular data format:   var hash_lookup = [];   // make can lookup nodes in o(1):   json.nodes.foreach(function(d, i) {     hash_lookup[d.id] = d;   });   json.links.foreach(function(d, i) {     d.source = hash_lookup[d.source];     d.target = hash_lookup[d.target];   }); 

i've tried debugging above, can't manage figure out. following error message (which means haven't set links correctly):

uncaught typeerror: cannot read property 'weight' of undefined

link full js: http://jsfiddle.net/9smrw/

here straightforward way this:

var edges = []; json.links.foreach(function(e) {     var sourcenode = json.nodes.filter(function(n) {         return n.id === e.source;     })[0],         targetnode = json.nodes.filter(function(n) {             return n.id === e.target;         })[0];      edges.push({         source: sourcenode,         target: targetnode,         value: e.value     }); });  force     .nodes(json.nodes)     .links(edges)     .start();  var link = svg.selectall(".link")     .data(edges)     ... 

here working plunk. (you should fork safe, in case inadvertently delete it.)


Comments