Define nodes index by record id

66 Views Asked by At

I'm trying to build a graph with d3 using this example: http://bl.ocks.org/jhb/5955887

Is the first time I try to use the d3 library and I'm trying to set the nodes with data coming from my database, this is an example of a node I want to build:

{
  index: 700,
  name: 'The person's name'
}

The data from the nodes came from a MySql table called Researchers, nothing more that a list of persons with their id and names: enter image description here

As you can see, each Researcher has a related array that contains all the related researchers and this will be used to build the edges. Below is the code for set the graph edges and nodes:

const g_nodes = [];
const g_edges = [];
/*For each researcher, set the edges related to that researcher*/
this.state.nodes.forEach(n => {
  if (n.related.length > 0) {
    n.related.forEach(r => {
      g_edges.push({
        source: n.id,
        target: r.id,
        weight: r.RelatedResearcher.cs + r.RelatedResearcher.bc
      });
    })
  }
})
/*For each researcher set his/her node on the graph*/
this.state.nodes.forEach(n => {
  g_nodes.push({
    index: n.id,
    name: n.name
  });
})
console.log(g_edges);
console.log(g_nodes);

This picture is from the console.log(g_nodes) and work as expected: enter image description here

The problem is that as soon as I put the edges and the nodes into the dataset object, the node's index change to the array position and the weight field appears on the node objects:

dataset.nodes = g_nodes;
dataset.edges = g_edges;
console.log(g_edges);
console.log(g_nodes);

enter image description here

When this happens, I get an error from d3:

TypeError: "r.source is undefined"

Then I look into the edges and the first edge receives undefined for the source and target:

0: Object { source: undefined, target: undefined, weight: 0.46782460000000003 }

Sorry about my, English and hope you can help. Thank you

0

There are 0 best solutions below