我有力导向图的节点和链接数据。链接之间可能有num
个,两个或三个链接:
{"nodes": [{"id": "Michael Scott", "type": "boss"}
,{"id": "Jim Halpert", "type": "employee"}
,{"id": "Pam Beasley", "type": "employee"}
,{"id": "Kevin Malone", "type": "employee"}
,{"id": "Angela", "type": "employee"}
,{"id": "Dwight Schrute", "type": "employee"}]
,"links": [{"source": "Michael Scott", "target": "Jim Halpert", "num": 1}
,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
,{"source": "Angela", "target": "Dwight Schrute", "num": 3}]
}
我有一个下拉列表,它应该基于num
驱动d3强制导向图的节点和链接的过滤。到目前为止,我有这个代码来过滤JSON节点和链接数据
var dropdown = d3.select("#selectLinkNumber")
var change = function() {
d3.selectAll("svg > *").remove()
var val = dropdown.node().options[dropdown.node().selectedIndex].value;
d3.json("test.json", function(error, graph) {
var filteredLinks = graph.links.filter(d => d.num >= val);
//Needs some way to map unique source and targets to id in nodes
var filteredNodes = graph.nodes.filter()//Needs some way to fill node filtering with mapping from filteredLinks
});
var filteredGraph = {
nodes: filteredNodes,
links: filteredLinks
};
//do stuff
})
}
dropdown.on("change", change)
change();
如何完成JavaScript数组操作代码以过滤掉基于num
的链接,并过滤掉相应的节点?
答案 0 :(得分:1)
您可以使用节点id
作为对象的键,以确保它们只添加一次,并且每个id
只过滤一次nodes数组。这假设没有节点链接到自身,但这将是一个不寻常的边缘情况。
var filteredNodes = Object.values(filteredLinks.reduce(function(t,v){
if(!t[v.source]){
t[v.source] = graph.nodes.filter(o => o.id === v.source)[0]
}
if(!t[v.target]){
t[v.target] = graph.nodes.filter(o => o.id === v.target)[0]
}
return t;
},{}))