Need an elegant way to map nodes and links ready for d3.js force graph. I tried using lodash but couldn't find a way. What I need is to extract all the nested objects into a new array on a single level and also, for each object, according to its deep index, to generate a new array of links with source and target properties... for example: if an object has 2 children, I need to generate 2 links where 'source' is the parent id and the 'target' is itself id.
Here is my input structure:
[
{
"id": 0,
"name":"Name0",
"linkType":"PROFESSIONAL",
"children":[
{
"id": 1,
"name":"Name1",
"linkType":"FAMILY",
"children":[
{
"id": 2,
"name":"Name2",
"linkType":"FAMILY",
"children":[
{
"id": 3,
"name":"Name3",
"linkType":"FAMILY"
},
{
"id": 4,
"name":"Name4",
"linkType":"FAMILY"
}
]
},
{
"id": 5,
"name":"Name5",
"linkType":"FAMILY"
}
]
},
{
"id": 6,
"name":"Name6",
"linkType":"FAMILY"
}
]
},
{
"id": 7,
"name":"Name7",
"linkType":"PROFESSIONAL",
"children":[
{
"id": 8,
"name":"Name8",
"linkType":"FAMILY",
"children":[
{
"id": 9,
"name":"Name9",
"linkType":"FAMILY"
},
{
"id": 10,
"name":"Name10",
"linkType":"FAMILY"
}
]
},
{
"id": 11,
"name":"Name11",
"linkType":"FAMILY",
"children":[
{
"id": 12,
"name":"Name12",
"linkType":"FAMILY",
"children":[
{
"id": 13,
"name":"Name13",
"linkType":"FAMILY"
},
{
"id": 14,
"name":"Name14",
"linkType":"FAMILY"
}
]
},
{
"id": 15,
"name":"Name15",
"linkType":"FAMILY"
}
]
}
]
}
]
The result arrays should be:
const nodes = [ //no matter the deep index... all the nodes will be on the same array
{
"name":"Name0",
"linkType":"PROFESSIONAL",
},
{
"name":"Name7",
"linkType":"PROFESSIONAL",
},
{
"name":"Name1",
"linkType":"FAMILY",
}
.
.
.
]
const links = [
{
id: 0, //first generated link
source: 0 // the source node id
target: 1 // the target node id -- node Name0 is linked with node Name1
},
{
id: 1,
source: 0
target: 2
},
{
id: 2,
source: 1
target: 2
}
.
.
.
]
