I have a set of JSON format data which needs to be converted into a mxGraph diagram.
here's how it should look like:
This is the structure of my JSON data
[
{
name: 'Globals',
parentObjects: []
},
{
name: 'Customer',
included: true,
parentObjects: [
{
name: 'Globals',
}
],
},
{
name: 'Product',
included: true,
parentObjects: [
{
name: 'Globals',
}
],
},
{
name: 'Transaction',
included: true,
parentObjects: [
{
name: 'Customer',
},
{
name: 'Product',
}
],
},
]
I am very new to mxGraph and I do not have much experience with it so any help would be much appreciated. Thank you.
I am also new to mxGraph and wanted a little learning session. So I tried it with your requirements.
I have created a fiddle from the example projects of mxGraph-js.
Here is the primary code that makes the magic:
var root = undefined;
...
var dict = {};
// run through each element in json
data.forEach(function (element) {
var name = element.name;
// create graph element
var graphElement = graph.insertVertex(parent, null, name, 20, 20, 80, 30);
// check if any parent element
if (element.parentObjects.length > 0) {
// run through each parent element
element.parentObjects.forEach(function (parentObj) {
var parentGraphElement = dict[parentObj.name];
// add line between current element and parent
graph.insertEdge(parent, null, '', parentGraphElement, graphElement);
});
} else {
// set root for layouting
root = graphElement;
}
// add element to dictionary. this is needed to find object later(parent)
dict[name] = graphElement;
});
...
// Creates a layout algorithm to be used with the graph
var layout = new mxHierarchicalLayout(graph, mxConstants.DIRECTION_NORTH);
// Moves stuff wider apart than usual
layout.forceConstant = 140;
if (root) {
layout.execute(parent, root);
}
Happy Coding, Kalasch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With