我正在自己的应用程序中编写代码,以完全按照您的要求进行操作。下面的代码有效,尽管我怀疑这不是最有效的方法。因此,请不要等待至少几天才能让经验丰富的人发布更好的答案或添加评论此答案的评论。
诀窍是query cy
(cytoscape.js核心对象)寻找仅包含具有给定id的节点的“ collection object”,然后查询集合对象以查看是否为empty。如果该节点不存在,请cy.add()
。如果该节点确实存在,请在集合对象上调用node.data()
对其进行更新。
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 even after updateGraph() returns.
当然gg
变量不是必需的,但是我发现它对于查看Chrome调试器中正在发生的事情是必不可少的。
在应用程序中,您可以在调用node.data()
之前调用Object.assign()
合并数据。这将比上面的代码更简单,更高效,在上面的代码中,来自源的数据具有与cytoscape.js期望的密钥不同的密钥。
,
//Node from source 1 => "id": "1","name": "1","param1": 100;
var xNode={"id": "1","param1": 100}
//Node from source 2 => "id": "1","param2": 200;
var yNode={"id": "1","param2": 200}
// finalNode=Object.assign({},xNode,yNode)
var finalNode={...xNode,...yNode}
console.log('merge Obj:'+JSON.stringify(finalNode))
本文链接:https://www.f2er.com/3059212.html