cytoscape.js - 如何合并来自不同来源的同一节点的属性

cytoscape.js - how to merge attributes of the same node from different sources

我有一个显示一些节点及其属性的工作图。然后我得到一个包含不同数据的 JSON,其中一些节点可能已经存在于我的图表中。如何合并两个数据源,使它们在同一个图表上都可见 - BUT 具有相同 ID 的节点必须合并为一个并包含两个 个数据源的属性(不只是一个,默认情况下)?

示例:

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

我正在自己的应用程序中编写代码来完全按照您的要求进行操作。下面的代码有效,但我怀疑这不是最有效的方法。所以,请不要在没有等待至少几天的情况下接受这个答案,等待更有经验的人 post 更好的答案或添加批评这个答案的评论。

诀窍是 query cy (the cytoscape.js core object) for a "collection object" containing just the node with the given id, and then query the collection object to see if it's empty. If the node doesn't exist, you cy.add() it. If the node does exist, you call 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 调试器中发生的事情是必不可少的。

在您的应用程序中,您可以先调用 Object.assign() 来合并数据,然后再调用 node.data()。这将比我上面的代码更简单、更有效,其中来自源的数据具有与 cytoscape.js.

预期的键不同的键

     //Node from source 1 => "id": "1", "name": "1", "param1": 100;

    var xNode={"id": "1", "name": "1", "param1": 100}

    //Node from source 2 => "id": "1", "name": "1", "param2": 200;
    var  yNode={"id": "1", "name": "1", "param2": 200}

   // finalNode=Object.assign({},xNode,yNode)
   var  finalNode={...xNode,...yNode}

   console.log('merge Obj:'+JSON.stringify(finalNode))