Read nodes and edges
Nodes and edges in the graph are embedded in NodeList and EdgeList data-structures.
In the following example, we show how we can iterate on those structures to print the ids to the console, and how those structures can be transformed into read-only Arrays.
Open in a new window.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../build/ogma.min.js"></script>
<style>
#graph-container { top: 0; bottom: 0; left: 0; right: 0; position: absolute; margin: 0; overflow: hidden; }
.info { margin: 5px; }
</style>
</head>
<body>
<div id="graph-container"></div>
<script>
'use strict';
var ogma = new Ogma({
container: 'graph-container'
});
// Generate a random Graph.
ogma.generate.random({
nodes: 50,
edges: 50
}).then(function (g) {
// Assign this graph to ogma.
ogma.setGraph(g);
ogma.view.locateGraph();
// METHOD 1 : using NodeList and EdgeList data structures (recommended)
// nodes
ogma.getNodes().forEach( function (node) {
// do something with the node
console.log(node.getId());
});
// edges
ogma.getEdges().forEach( function (edge) {
// do something with the edge
console.log(edge.getId());
});
// Chaining operations on NodeLists to obtain the list of node ids
var ids = ogma.getNodes().getId().join(), i;
console.log('Node ids ', ids);
// Transforming the NodeList and EdgeList into Arrays (slowest)
// nodes
var nodeArray = ogma.getNodes().toArray();
for (i = 0; i < nodeArray.length; i++) {
console.log(nodeArray[i].getId());
}
// edges
var edgeArray = ogma.getEdges().toArray();
for (i = 0; i < edgeArray.length; i++) {
console.log(edgeArray[i].getId());
}
});
</script>
</body>
</html>