转换JSON数组的对象,从两个属性值创建新的属性

transform JSON array of objects, create new property from two property values

本文关键字:属性 两个 创建 数组 JSON 对象 转换      更新时间:2023-09-26

我有一些JSON数据看起来像这样,其中每个对象有三个属性:

data = [
      { 
          "country" : "Ireland", 
          "year" : "2013",
          "number" : 45
      },
      { 
          "country" : "Ireland", 
          "year" : "2014",
          "number" : 23430 
      },
      { 
          "country" : "Honduras", 
          "year" : "2013",
          "number" : 1582
      },
      { 
          "country" : "Honduras", 
          "year" : "2014",
          "number" : 3458
      }
    ]

我想转换我的数据,使每个对象只有两个属性。名为"country"的属性将保持不变。我想把另外两个属性结合起来,让"year"的值成为新属性的key,"number"的值就是新属性的值。新的JSON对象数组如下所示:

    newData = [
      { 
          "country" : "Ireland", 
          "2013" : 45, 
          "2014" : 23430
      },
      { 
          "country" : "Honduras", 
          "2013" : 1582, 
          "2014" : 3458
      }
    ]

我该怎么做呢?我做了很多调查,但还是找不到解决办法。我更喜欢用javascript来做这个,而不是一个库。

只需遍历每个数据项并向结果数组中添加项。您可以创建一个地图来跟踪您在迭代中看到的国家,以便快速访问。

var newData = [],
    countries = {};
data.forEach(function (d) {
    var country = countries[d.country];
    if (!country) {
        newData.push(country = countries[d.country] = {});
    }
    country[d.year] = d.number;
});

对不起,这是这次javascript的答案:

country_data = new Array();
for(l in data){
    if(typeof(country_data[data[l].country]) == 'undefined'){
       country_data[data[l].country] = new Array();
    }
    country_data[data[l].country].country = data[l]['country'];
    country_data[data[l].country][data[l].year] = data[l]['number'];
}
new_arr = new Array();
for(v in country_data){
    new_arr.push(country_data[v])
}
console.log(new_arr);

输入链接描述