我有一个工作图,显示了一些节点及其属性。然后,我得到了具有不同数据的JSON,图中的某些节点可能已经存在。如何组合两个数据源,以使它们在同一图形上可见-具有相同ID的BUT节点必须合并为一个,并包含来自[[both数据源的属性(不仅仅是从一个,默认情况下)?
示例:Node from source 1 => "id": "1", "name": "1", "param1": 100;
Node from source 2 => "id": "1", "name": "1", "param2": 200;
我希望在图表上看到的是一个具有属性的节点:
"id": "1", "name": "1", "param1": 100, "param2": 200
诀窍是query cy
(cytoscape.js核心对象)为“ collection object”,仅包含具有给定id的节点,然后查询集合对象以查看其是否为empty。如果该节点不存在,则将其cy.add()
。如果该节点确实存在,则在集合对象上调用cy.add()
以对其进行更新。
当然node.data()
变量不是必需的,但是我发现它对于查看Chrome调试器中发生的事情是必不可少的。在您的应用程序中,您可以在调用
function updateGraph(g) { // g is the output from JSON.parse(), containing graph from server gg = g; // save pointer to g, for console debugging // Import nodes from server graph for (const sn of g.nodes) { // sn = node as represented on the server var node = cy.$id(sn.id) // node = cytoscape.js's representation of node if (node.empty()) { node = cy.add({group: 'nodes', data: { id: sn.id, label: sn['display-name'], // peculiar to my application parent: sn.memberOf // peculiar to my application /* . . . and whatever other data you want to copy to the cytoscape.js graph . . . */ }}); node.addClass(sn.class); } else { /* Update `node` with data from `sn`.*/ node.data( /* your overriding data goes here */ ); } } var gg; // We save the last graph dict from the server here so we can look at // it in the Chrome debugger.
或gg
之前调用Object.assign()
合并数据。这将比上面的代码更简单,更高效,在上面的代码中,来自源的数据的密钥与cytoscape.js期望的密钥不同。