2017-10-08 2 views
0

私はこのようになりますJSONファイルがあります。再手配JSONファイル

[ 
    { 
    "id": 1, 
    "country": "Greece", 
    "names": [ 
     "Alex", 
     "Betty", 
     "Catherine", 
     "Dave", 
     "Edward", 
     "Frank", 
     "George", 
     "Helen", 
     "Irene" 
    ] 
    }, 
    { 
    "id": 2, 
    "country": "US", 
    "names": [ 
     "John", 
     "Alex", 
     "Edward", 
     "Kate", 
     "Robert", 
     "Irene", 
     "Tim", 
     "Sam" 
    ] 
    }, 
    { 
    "id": 3, 
    "country": "France", 
    "names": [ 
     "Helen", 
     "Kate", 
     "Louise", 
     "Tim", 
     "Catherine", 
     "Arthur", 
     "Frank", 
     "Natalie", 
     "Dave" 
    ] 
    }, 
    { 
    "id": 4, 
    "country": "India", 
    "names": [ 
     "Ritesh", 
     "Alex", 
     "Betty", 
     "Robert" 
    ] 
    }, 
    { 
    "id": 5, 
    "country": "India", 
    "names": [ 
     "Nafeez", 
     "Tom", 
     "Natalie", 
     "Gunar", 
     "Louise", 
     "Arthur" 
    ] 
    } 
] 

を、私はそれが「中心名」ことと次のようになりたい:

{ 
"groups": [  
    { 
    "gr_id":1 
    "name":"Alex", 
    "country":"Greece" 
    }, 
    ......... 
    { 
    "gr_id":1 
    "name":"Irene", 
    "country":"Greece" 
    }, 


    { 
    "gr_id":2 
    "name":"John", 
    "country":"US" 
    .......... 
    { 
    "gr_id":2 
    "name":"Sam", 
    "country":"US" 
    }, 


    { 
    "gr_id":3 
    "name":"Helen", 
    "country":"France" 
    }, 
    ......... 
    { 
    "gr_id":3 
    "name":"Dave", 
    "country":"France" 
    }, 


    { 
    "gr_id":4 
    "name":"Ritesh", 
    "country":"India" 
    }, 
    ........ 
    { 
    "gr_id":4 
    "name":"Robert", 
    "country":"India" 
    }, 

    { 
    "gr_id":5 
    "name":"Nafeez", 
    "country":"India" 
    }, 
    ........... 
    { 
    "gr_id":5 
    "name":"Arthur", 
    "country":"India" 
    } 
     ], 
"links": [  
    { 
    "source":"Alex" 
    "target":"Irene", 
    "count":1 
    "country":"Greece" 
    }, 
    ... 
    { 
    "source":"Alex" 
    "target":"Arthur", 
    "count":0 
    "country":"India" 
    }, 
    ... 
     ] 
} 
私はこのような各国/名(csv形式)の隣接行列持っ Linkscountの場合

screenshot of csv file (ad. matrix for India)

このJSONは単なる一例です。私ははるかに大きなファイルを持っています(私はD3のグラフの視覚化のために必要です)

+0

私はこれを使用して終了:グラフ= graph_r.nodes.reduce( (ACC、CURR)=> acc.concat( curr.name.map(項目=>({ gr_id:curr.id、 国:curr.country、 名:項目 })) )、 [] )。 – user8734221

答えて

1

Reduce()map()はこれで完璧に動作します。これは、基本的に各項目を取得し、その後、名前の上にマッピングし、アレイにmap()の結果を追加:

let obj = {} 
obj.groups = json.reduce(
    (acc, curr) => acc.concat(curr.names.map(
    item => ({gr_id: curr.id, country: curr.country, name: item}) 
    )), []) 

console.log(obj) 

// { groups: 
// [ { gr_id: 1, country: 'Greece', name: 'Alex' }, 
//  { gr_id: 1, country: 'Greece', name: 'Betty' }, 
//  ...etc 
//  ] 
// } 
関連する問題