Bla*_*air 19 javascript json d3.js
我试图用ID而不是索引链接d3节点(节点ID由我的应用程序生成).
这是我的节点:
"Nodes": [
{
"Id": "338",
"Name": "TEST NODE ONE",
"Url": "http://www.google.com"
},
{
"Id": "340",
"Name": "TEST NODE TWO",
"Url": "http://www.yahoo.com"
},
{
"Id": "341",
"Name": "TEST NODE THREE",
"Url": "http://www.stackoverflow.com"
},
{
"Id": "342",
"Name": "TEST NODE FOUR",
"Url": "http://www.reddit.com"
}
]
Run Code Online (Sandbox Code Playgroud)
它们目前通过索引链接:
"links": [
{
"source": 0,
"target": 0,
"value": "0"
},
{
"source": 0,
"target": 1,
"value": "0"
},
{
"source": 1,
"target": 2,
"value": "0"
},
{
"source": 3,
"target": 2,
"value": "0"
}
]
Run Code Online (Sandbox Code Playgroud)
但是,我想通过"Id"链接它们:
"Links": [
{
"Source": "338",
"Target": "338",
"Value": "0"
},
{
"Source": "338",
"Target": "340",
"Value": "0"
},
{
"Source": "340",
"Target": "341",
"Value": "0"
},
{
"Source": "342",
"Target": "341",
"Value": "0"
}
]
Run Code Online (Sandbox Code Playgroud)
我尝试过这里提出的解决方案:https://groups.google.com/forum/#!msg/d3-js/LWuhBeEipz4/0kZIojCYvhIJ
通过在调用force.nodes之前添加以下行:
// make links reference nodes directly for this particular data format:
var hash_lookup = [];
// make it so we can lookup nodes in O(1):
json.Nodes.forEach(function(d, i) {
hash_lookup[d.Id] = d;
});
json.Links.forEach(function(d, i) {
d.source = hash_lookup[d.Source];
d.target = hash_lookup[d.Target];
});
Run Code Online (Sandbox Code Playgroud)
我已经尝试过调试上面的内容,但我无法弄明白.我收到以下错误消息(这通常意味着我没有正确设置链接):
Uncaught TypeError: Cannot read property 'weight' of undefined
链接到我的完整JS:http://jsfiddle.net/9sMrw/
Fer*_*des 26
这是一种直接的方法:
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)
...
Run Code Online (Sandbox Code Playgroud)
这是一个工作的PLUNK.(如果我无意中将其删除,您应该将其分叉以保证安全.)
归档时间: |
|
查看次数: |
11241 次 |
最近记录: |