Currently, I'm diving into creating a data visualization using d3js paired with hierarchical layout. The data I am working with has the following structure:
0
/ | \
/ | \
1 5 3
\ | |
\ | |
4 /
| /
2
Since I am unable to create links to multiple parents, I have resorted to duplicating nodes for display purposes:
0
/ | \
/ | \
1 5 3
| | |
| | |
4 4 |
| | |
2 2 2
To illustrate my issue, I have set up a fiddle demo:
- Using the correct data in my JSON input results in the expected layout (graphic outlined in blue).
- However, when I use a loop to parse my JSON input, it leads to a distorted graph (graphic outlined in green).
Here is the loop I utilized to parse the input:
for (i in root[2].Arcs){
var d = root[1].Nodes[root[2].Arcs[i].D];
var s = root[1].Nodes[root[2].Arcs[i].S];
if (!d.children){
d.children = [];
}
d.children.push(s);
}
Although the printed elements in the console appear to be the same, the layout render differs, possibly due to variations in object reference.
One workaround I discovered is to decode and encode my variable:
var root = JSON.parse(JSON.stringify(root));
Following this approach, the script functions correctly. However, if 'root' is a lengthy array, the parsing process becomes time-consuming...
Any insights on why encoding/decoding is necessary to display identical content would be greatly appreciated.
Thanks