JSON Group By关于它的价值

时间:2016-02-15 10:59:43

标签: jquery json

我有一个类似于下面提到的json,其中我想打破这个JSON相对于最后添加的年份

[
  {
    "GroupWithYear": "pakistan-2016"
  },
  {
    "GroupWithYear": "Headquarters-2016"
  },
  {
    "GroupWithYear": "pakistan-2015"
  },
  {
    "GroupWithYear": "USA-2015"
  },
  {
    "GroupWithYear": "Headquarters-2015"
  }
]

我想要那样的结果

[
  {
    "name": "2016",
    "categories": [
      "Pakistan",
      "HeadQuarters"
    ]
  },
  {
    "name": "2015",
    "categories": [
      "Pakistan",
      "HeadQuarters",
      "USA"
    ]
  }
]

请告诉我如何实现这一目标,还是有任何可以帮助我转换此功能的实用程序

1 个答案:

答案 0 :(得分:0)

试试这段代码。

   var input=[
  {
    "GroupWithYear": "pakistan-2016"
  },
  {
    "GroupWithYear": "Headquarters-2016"
  },
  {
    "GroupWithYear": "pakistan-2015"
  },
  {
    "GroupWithYear": "USA-2015"
  },
  {
    "GroupWithYear": "Headquarters-2015"
  }
];
var output=[];
function checkYear(element, index, array){

}
input.forEach(function(value){
    var year=value.GroupWithYear.split('-')[1];
    var country=value.GroupWithYear.split('-')[0];
    var name=output.find(x=> x.name==year);
    if(!name){
        output.push({
            name:year,
            categories:[]
        });
    }
    var categories=output.find(x=> x.name==year).categories;
    categories.push(country);
});
console.log(output);