gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:56:14 25 4
gpt4 key购买 nike

我有力定向图的节点和链接数据。链接之间可能有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com