json - 过滤 D3 网络图的 JSON 数据
问题描述
我正在使用 JSON 数据在 D3 中构建网络图,并根据用户输入动态构建节点和链接。例如:有一个下拉菜单(由 JSON 填充),用户可以为“美学”选择一个域图(查看所有关于美学的文章),然后为“生物学”选择一个域图(查看所有关于生物学)等。但是我一直遇到一个我一生都无法解决的特定问题:每当我重新运行图表(比如重新选择“美学”)时,我都会丢失链接上的所有信息。我确切地知道代码中发生这种情况的位置,但我不明白为什么。而且我想知道我是否没有正确提取 JSON 数据,或者需要重置一些奇怪的数据缓存。如果有人有任何想法,我将非常感谢。
JSON 的结构如下:
{
"articles": {
"nodes": [
{
"id": "/entries/emotions-17th18th/",
"title": "17th and 18th Century Theories of Emotions",
"primary_domain": "Mind"
}, etc, etc,
],
"links": [
{
"source": "/entries/emotions-17th18th/",
"target": "/entries/aesthetics-18th-british/"
},
{
"source": "/entries/emotions-17th18th/",
"target": "/entries/aesthetics-18th-french/"
},etc, etc
]
}
}
在我的文件的开头,我像这样拉入 JSON:
d3.json('static/network.json').then(function(data) { startVisualization(data)} );
然后从 startVisualization 内部,我将数据对象传递给各种函数以动态构建图形。
当用户选择要绘制的域时,这是处理请求的函数:
function getDomainDataFromJSON(data, domainTitle) {
let sourceLinks = [];
let domainLinks = [];
let domainData = {};
// filter JSON for all the articles tagged in domainTitle
let domainNodes = data.articles.nodes.filter(dnode => {
return dnode.primary_domain === domainTitle
})
// ****** The problem is happening in these two code blocks, and I can't figure out why *******
// ****** The first weird thing is that on the second run, the sourcelinks return a different number,
// ****** like data.articles.links has been changed.
// get the source (outgoing) links for each article contained in domainNodes
domainNodes.forEach(snode => {
data.articles.links.forEach(slink => {
if (snode.id === slink.source) {
sourceLinks.push(slink)
}
})
})
console.log("sourcelinks:")
console.log(sourceLinks)
// ****** The second weird thing is that on the second run, nothing is returned here at all
// select only those links in sourceLinks that have a target that is one of the articles in domainNodes
domainNodes.forEach(tnode => {
sourceLinks.forEach(tlink => {
if (tnode.id === tlink.target) {
domainLinks.push(tlink)
}
})
})
//store the domain data as an object to return to calling function
domainData = { "search": domainTitle,
"nodes": domainNodes,
"links": domainLinks }
return domainData
}
我第一次在域上运行 getDomainDataFromJSON() 时,一切正常。下次我返回图表时,我不会返回任何链接。我不认为问题出在 d3 生成代码中,因为 getDomainDataFromJSON() 返回一个对象,并且每次重新运行图形时,都不会填充任何链接。
您可以在此处查看控制台的输出,显示计数如何变化: 控制台输出
谢谢,感谢您对任何人的帮助。
解决方案
推荐阅读
- python - 指定 f 字符串中连接变量的宽度
- github-pages - GitHub Pages repo 没有加载工作,我搞砸了什么?
- arrays - 切片numpy数组
- html - 使 CSS 动画更轻量级或修复浏览器之间的视频颜色差异
- nestjs - Nestjs 捕获 500 错误并返回错误
- javascript - 如何防止 PHP 回显结束 JS 字符串?
- java - 必须定义 GOOGLE_APPLICATION_CREDENTIALS。如何在 Heroku 上的 Java Spring 中设置环境变量?
- html - 从网站上抓取的一串文本创建名称数组
- java - 如何使用 java 在 Internet 上创建、访问和编辑 csv 文档
- java - 为什么只有少量的Java库里面包含module-info.class?