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

前端 未结 6 672
旧时难觅i
旧时难觅i 2020-12-09 16:31

I tried setting both nodes and links at the same time this way:

var force = d3.layout.force()
    .size([w, h])
    .nodes(nodes)
    .links(connections)
            


        
6条回答
  •  旧巷少年郎
    2020-12-09 17:32

    Thanks to the answers above which refer to null source or target values!

    I've been testing out the graph from http://bl.ocks.org/mbostock/4062045, and found that my data referenced a missing node.

    This may help others debug this issue:

    d3.json("my-buggy-data.json", function(error, graph) {
    
        // Find blank links, which give the error
        // "Uncaught TypeError: Cannot read property 'weight' of undefined"
        graph.links.forEach(function(link, index, list) {
            if (typeof graph.nodes[link.source] === 'undefined') {
                console.log('undefined source', link);
            }
            if (typeof graph.nodes[link.target] === 'undefined') {
                console.log('undefined target', link);
            }
        });
    
        force
            .nodes(graph.nodes)
            .links(graph.links)
            .start();
    

提交回复
热议问题