如何更改Json格式?

时间:2016-04-15 10:13:28

标签: jquery json

我正在获得如下的JSON格式

[{
    "year": "2015-01-05",
    "contentTitle": "bus",
    "aid": 43050500
}, {
    "year": "2015-01-14",
    "contentTitle": "paratransit",
    "aid": 1435400
}]

但我需要格式如下

[
  {
    "year": "2015-01-05",
    "bus": 43050500,
    "paratransit": 1435400,
    "rail": 174436000
  },
  {
    "year": "2015-01-14",
    "bus": 420572700,
    "paratransit": 1924800,
    "rail": 168658800
  }]

我尝试使用以下

进行存档
data.forEach(function (d) { 

    var gameName = d.contentTitle;  
     var gameValue = d.aid; 
        d[gameName] = gameValue;
        d.year = parseformat(d.year);
        delete d["contentTitle"];
        delete d["aid"];


    });

    alert(JSON.stringify(data));

但我没有按预期得到。

1 个答案:

答案 0 :(得分:0)

你应该map你的数组而不是forEach

data = [{
  year: "2015-01-05",
  contentTitle: "bus",
  "aid": 43050500
}, {
  year: "2015-01-14",
  contentTitle: "paratransit",
  aid: 1435400
}];

data = data.map(function (d) {
    d[d.contentTitle] = d.aid;
    d.year = d.year; // parseformat me <<
    delete d["contentTitle"];
    delete d["aid"];

    return d;
});

alert(JSON.stringify(data));