在 D3 中对链接使用不同的命名约定

Using a Different Naming Convention for Links in D3

是否可以更改 D3 中被视为 "links" 的内容?我从服务器收到的 JSON 设置为 "nodes" 和 "edges" 而不是 "nodes" 和 "links"。这是一个示例 JSON:

{
"nodes": [
{"fixed":true,"data": {"id": "foo","idType":"USERNAME","color":"red"},"selected":false},
{"fixed":true,"data": {"id": "bar","idType":"USERNAME","color":"yellow"},"selected": false}
],
"edges": [
{"classes":null,"data":{"color":"blue","source":"foo","target":"bar","visible":true},"grabbable":false},
{"classes":null,"data":{"color":"green","source":"bar","target":"foo","visible":true},"grabbable":false}
]}

一开始以为是从

声明的
var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

然而,当我将 .link 更改为 .edge 时,我的代码中断了。

// sets the source and target to use id instead of index
var edges = [];
root.edges.forEach(function(e) {
    var sourceNode = root.nodes.filter(function(n) {
                return n.data.id === e.data.source;
            })[0],
            targetNode = root.nodes.filter(function(n) {
                return n.data.id === e.data.target;
            })[0];

    // push the attributes in the JSON to the edges.
    edges.push({
        source: sourceNode,
        target: targetNode,
        label: e.data['label'],
        color: e.data['color']
    });
});

force
        .nodes(root.nodes)
        .links(edges)
        .start();

link = link
        .data(edges)
        .enter().append("line")
        .attr("class", "link")
        .style("stroke-width", 1.5);

node = node
        .data(root.nodes)
        .enter().append("g")
        .attr("class", "node");

Halcyon 关于 d3 不关心你所说的内容的评论 links 让我意识到我的代码并没有脱离图形的实际初始化。它打破了我将 id 用作 source/target 而不是默认 index 的方式。

root.links.forEach... 更改为 root.edges.forEach... 解决了该问题。