add nodes and edges through loop in cytoscape arbo

2019-07-21 10:21发布

问题:

I want to add more than 10 nodes in arbor.js layout.This code adds nodes and edges in arbor layout for cytoscape

 elements: {

            nodes: [
                { data : { id: b[0], faveBorderColor: "#AAAAAA", name: b[0], faveColor: "#EEB211", faveFontColor: "#ffffff" ,'link':'http://www.yahoo.com'} },
                { data : { id: a[0], name: a[0], faveColor: "#21526a", faveFontColor: "#fff"} },
                { data : { id: a[1], name: a[1], faveColor: "#21526a", faveFontColor: "#fff"} },
                { data : { id: a[2], name: a[2], faveColor: "#21526a", faveFontColor: "#fff"} },
                { data : { id: a[3], name: a[3], faveColor: "#21526a", faveFontColor: "#fff"} },
                { data : { id: a[4], name: a[4], faveColor: "#21526a", faveFontColor: "#fff"} }
            ], //end "nodes"

            edges: [
                { data : { target: a[0], source : b[0] } },
                { data : { target: a[1], source : b[0]} },
                { data : { target: a[2], source : b[0]} },
                { data : { target: a[3], source : b[0]} },
                { data : { target: a[4], source : b[0]} }
            ]//end "edges"
        },//end "elements"

Now i have 100s of nodes to be added. a[] and b[] are arrays which gets data dynamically through mysql. Is there any chance to loop through nodes, so that all the data can be added dynamically.

回答1:

You can add elements to the graph in a loop with cy.add():

// assuming your graph object is available as 'cy' e.g. by
var cy = cytoscape({
    container: document.getElementById('cy')
});

a = your array
b = the other array

for (var i=0; i<a.length; i++) {

    var name = a[i]

    cy.add([
        {group: "nodes", data: {id: name, ... }},
        { group: "edges", data: { id: a[i]+b[0], source: a[i], target: b[0]},...}
    ])
};

This will add all nodes from array a and add an edge to the first element of b. Nodes are identified by their id and nodes with existing ids are not added again. How you figure out which nodes from a and b are connected depends on your data structure of course.

You can rerun the layout with:

cy.layout( ... );


回答2:

Thanks for the reply.It pushed me in a right direction. I performed this with simple loops as I had to change my whole layout to implement this.

var demoNodes = [];
var demoEdges = [];

demoNodes.push({

    data: {
        id: b[0],
        name:b[0]
    }
});

for (var i = 0; i < a.length; i++) {
    demoNodes.push({

        data: {
            id: a[i],
            name:a[i]
        }
    });
}



for (var i = 0; i < a.length; i++) {
    demoEdges.push({
        data: {
            source: b[0],
            target: a[i]

        }
    });
}

and put these values in elements

elements: {
            nodes: demoNodes,
            edges: demoEdges
        },

It worked out pretty well.