重新安排JSON文件(使用邻接矩阵)

时间:2017-10-08 02:03:09

标签: json csv d3.js matrix transform

我有一个如下所示的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"
    },
    ... 
        ]   
}

对于count中的Links,我对每个国家/地区/名称(csv格式)都有一个邻接矩阵,如下所示:screenshot of csv file (ad. matrix for India)

这个json就是一个例子。我有更大的文件(我需要它用于D3图形可视化)

1 个答案:

答案 0 :(得分: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
//     ]
//  }