1

您好,我正在尝试从对象中提取一些信息以创建图形,但它返回未定义我的对象看起来像

{
"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"
     },....
]
}

我想让一个对象看起来像

const data = {
    nodes: [{ id: 'Proche' }, { id: 'Loin' },{ id: 'Here' } ...],
    links: [{ source: 'Proche', target: 'Loin' }, { source: 'Here', target: 'Loin' },...]
};

我想在链接中提取名称而不是 id,但对象弧只有 es6 中的代码的 id,谢谢你帮助我

4

1 回答 1

0

您可以循环concepts使用 using for...of。填充nodes数组和一个map对象。该map对象具有id_cpt作为键和fr_cpt作为值。

{
  "1": "Proche",
  "2": "Loin",
  "3": "Here"
}

此对象可用于获取source和的targetlinks。然后循环arcslinks使用map对象创建

这是一个片段:

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)

于 2019-05-03T12:35:24.723 回答