javascript - 将过滤的 JSON 链接映射到过滤 JSON 节点

标签 javascript json d3.js svg

我有力定向图的节点和链接数据。链接之间可能有 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过滤出链接,并过滤出相应的节点?

最佳答案

您可以使用节点id作为对象的键,以确保它们仅添加一次,并且每个id节点数组仅过滤一次。这假设没有节点链接到自身,但这将是一种不寻常的边缘情况。

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;
},{}))

关于javascript - 将过滤的 JSON 链接映射到过滤 JSON 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44933506/

相关文章:

javascript - WebdriverJS 设置视口(viewport)大小

javascript - 字符集有什么问题?

javascript - 更改 D3-legend 中符号的颜色

javascript - nvd3线形图y2axis时间格式问题

html - d3 节点标记

javascript - 从 PHP 中返回多个值并在 Javascript 中解析的最佳方法

javascript - 在 React setState 中使用变量将元素从一个数组移动到另一个数组?

javascript - 在动画中将 div 元素移动到屏幕中间

javascript - MVC 无法在 View 中为 javascript 中的变量创建 json 字符串

c# - 谁能一眼就告诉我为什么这个 Action 这么慢?