Skip to content
  1. Examples

Read nodes and edges

This example shows how to retrieve nodes and edges from your Ogma instance. It uses the getNodes and getEdges methods to retrieve the nodes and edges from the graph. They return NodeList and EdgeList objects, which are iterable and can be transformed into read-only Arrays.

js
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container'
});

// Generate a random Graph.
ogma.generate
  .random({
    nodes: 50,
    edges: 50
  })
  .then(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(node => {
      // do something with the node
      console.log(node.getId());
    });
    // edges
    ogma.getEdges().forEach(edge => {
      // do something with the edge
      console.log(edge.getId());
    });

    // Chaining operations on NodeLists to obtain the list of node ids
    let ids = ogma.getNodes().getId().join(),
      i;
    console.log('Node ids ', ids);

    // Transforming the NodeList and EdgeList into Arrays (slowest)
    // nodes
    const nodeArray = ogma.getNodes().toArray();
    for (i = 0; i < nodeArray.length; i++) {
      console.log(nodeArray[i].getId());
    }
    // edges
    const edgeArray = ogma.getEdges().toArray();
    for (i = 0; i < edgeArray.length; i++) {
      console.log(edgeArray[i].getId());
    }
  });
html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />

    <link type="text/css" rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="graph-container"></div>
    <script src="index.js"></script>
  </body>
</html>
css
#graph-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  margin: 0;
  overflow: hidden;
}
.info {
  margin: 5px;
}