【问题标题】:Returning an array of objects from other object从其他对象返回对象数组
【发布时间】:2019-05-03 11:08:03
【问题描述】:

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

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

【问题讨论】:

    标签: javascript arrays ecmascript-6 es6-map


    【解决方案1】:

    您可以使用for...of 循环访问concepts。填充 nodes 数组和 map 对象。 map 对象以 id_cpt 作为键,fr_cpt 作为值。

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

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

    这是一个sn-p:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      相关资源
      最近更新 更多