D3 Linking nodes based on names rather than index

后端 未结 2 664
南笙
南笙 2020-12-11 22:17

I am trying to link the nodes based on Id rather than the index in this codepen, I am not able to figure out how to do it.

The following works:

var l         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 23:18

    You can do it like this: https://codepen.io/anon/pen/yqJoje?editors=0011

    I basically filter the nodes array to look for the x and y data relating to the target and source, then assign these to a value for use in your path assignment. Relevant code is here:

    function tick() {
      link.attr("d", function(d) {
        var curData = {
          target: nodes.filter(function (n) {
                    if (n.id == d.target) {
                      return { x: d.x, y: d.y };
                    }
                  })[0],
          source: nodes.filter(function (n) { 
                    if (n.id == d.source) {
                      return { x: d.x, y: d.y };
                    }
                  })[0]
        };
               ...
               ...
    }
    

    Note: Not sure if filtering through an array in the tick function is a good idea as it is probably going to cause performance issues down the line if a lot of nodes are generated. The tick function is being called a lot.

提交回复
热议问题