D3 force layout – linking nodes by name instead of index

Here is a straightforward way to do 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 is a working PLUNK. (You should fork it to be safe, in case I inadvertently delete it.)

Leave a Comment