从其他对象返回对象数组

Returning an array of objects from other object

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

{
"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,谢谢你帮助我

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

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

此对象可用于获取 linkssourcetarget 值。然后遍历 arcs 并使用 map object

创建 links

这是一个片段:

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)