如何在javascript中重新格式化JSON?

时间:2015-12-06 02:52:32

标签: javascript jquery json ajax

目前我的ajax请求是以这种格式获取JSON:

    {
        id: 1,
        teamname: "Chicago Blackhawks",
        league: NHL
        wins: 5
        losses: 10
        account_id: 3444,
    },
    {
        id: 2,
        teamname: "Chicago Bulls",
        league: NBA
        wins: 15
        losses: 2
        account_id: 3444,
    }

但要使用autocomplete jquery plugin,我需要这种格式:

[
   { value: 'Chicago Blackhawks', data: { category: 'NHL' } },
   { value: 'Chicago Bulls', data: { category: 'NBA' } }
]

基本上我只需要获取两个字段并将其格式化为值和数据 - >类别而不是名称和联赛。最好的方法是什么?

4 个答案:

答案 0 :(得分:4)

您的数据包含一些拼写错误,但一旦您修复了这些错误:

var data  = [{
    id: 1,
    teamname: "Chicago Blackhawks",
    league: "NHL",
    wins: 5,
    losses: 10,
    account_id: 3444,
},
{
    id: 2,
    teamname: "Chicago Bulls",
    league: "NBA",
    wins: 15,
    losses: 2,
    account_id: 3444,
}];

您可以从中提取所需的列表:

var newData = data.map(function(d) {
  return {
    value: d.teamname,
    data: {category: d.league}
  };
});

newData[0];
//=> Object {value: "Chicago Blackhawks", data: "NHL"}

Ack。感谢Salman进行更正。

答案 1 :(得分:1)

为了使得到的对象中的data键具有对象表示法,您应该稍微修改@湖南的答案中的代码,如下所示:

var newData = data.map(function(d) {
  return {
    value: d.teamname,
    data: {"category": d.league}
  };
});

答案 2 :(得分:1)

试试这个,

var jsonData  = [{
    id: 1,
    teamname: "Chicago Blackhawks",
    league: "NHL",
    wins: 5,
    losses: 10,
    account_id: 3444,
},
{
    id: 2,
    teamname: "Chicago Bulls",
    league: "NBA",
    wins: 15,
    losses: 2,
    account_id: 3444,
}];

function formatJson(jsonData){

  var rslt = [];
  for(var i = 0; i < jsonData.length; i++)
    rslt.push({ value: jsonData[i].teamname, data: { category: jsonData[i].league} });

   return rslt;
}

var mydata = formatJson(jsonData);

答案 3 :(得分:1)

假设您的JSON有效且@ Anik1991正确无误。您可以执行以下操作:

var json = '{"teams":[{"id": 1,"teamname": "Chicago Blackhawks","league": "NHL","wins": 5,"losses": 10,"account_id": 3444},{"id": 2,"teamname": "Chicago Bulls","league": "NBA","wins": 15,"losses": 2,"account_id": 3444}]}';

// convert your JSON to an object so you can retrieve values you need
var obj = JSON.parse(json);

// create a new array to store your values in the desired format
var newObj = [];

//for each team in obj, push the values you need as an object
obj['teams'].forEach(function(team){
  newObj.push({
    value: team.teamname,
    data: {
      category: team.league
    }
  });
});

// Finally use JSON.stringify to convert newObj to JSON
console.log(JSON.stringify(newObj));

请参阅https://jsfiddle.net/hsxgrom6/