d3.js: "Cannot read property 'weight' of undefined" when manually defining both nodes and links for force layout

I encounter same problem before, it is due to there is null values in source/target of links. print out nodes and links information might help to debug


The force-directed layout uses edge weights to calculate the layout. Try adding a dummy "weight":1 to all of your connections.

The code that initializes the links looks like this:

links.forEach(function(d) {
    if (typeof d.source == "number") { d.source = nodes[d.source]; }
    if (typeof d.target == "number") { d.target = nodes[d.target]; }
});

Presumably you could tweak that (in the d3 source) to use any property/type.


In addition to the answers mentioning the null in the source/target of links, the reason for this could be the assignment of an out-of-range source/target. E.g. you have 10 nodes and you assign the target to be the 11-th indexed node.