Hello am trying to extract some information from an object to create a graph but it returns undefined my object looks like
{
"concepts": [
{
"id_cpt": "1",
"fr_cpt": "Proche",
},
{
"id_cpt": "2",
"fr_cpt": "Loin",
}{
"id_cpt": "3",
"fr_cpt": "Here",
},...
],
"arcs": [
{
"idfrom":"1",
"idto":"2"
},
{
"idfrom":"3",
"idto":"2"
},....
]
}
I want to make an object looks like
const data = {
nodes: [{ id: 'Proche' }, { id: 'Loin' },{ id: 'Here' } ...],
links: [{ source: 'Proche', target: 'Loin' }, { source: 'Here', target: 'Loin' },...]
};
I want extract names not ids in links but the object arcs only have ids the code in es6 and thank you for helping me
You could loop through the concepts
using for...of
. Populate the nodes
array and a map
object. The map
object has id_cpt
as key and fr_cpt
as value.
{
"1": "Proche",
"2": "Loin",
"3": "Here"
}
This object can be used to get the source
and target
value for links
. Then loop through arcs
and create links
using map
object
Here's a snippet:
const input = {"concepts":[{"id_cpt":"1","fr_cpt":"Proche",},{"id_cpt":"2","fr_cpt":"Loin",},{"id_cpt":"3","fr_cpt":"Here",},],"arcs":[{"idfrom":"1","idto":"2"},{"idfrom":"3","idto":"2"},]}
let nodes = [],
links = [],
map = {};
for (const { id_cpt, fr_cpt } of input.concepts) {
nodes.push({ id: fr_cpt });
map[id_cpt] = fr_cpt
}
for (const { idfrom, idto } of input.arcs) {
links.push({ source: map[idfrom], target: map[idto] }) // get the value using map
}
const output = { nodes, links }
console.log(output)