0

我有这种格式的数据。这是 BaaS 用于游戏开发的 gamesparks 数据。

我正在将此数据发送给 IOS 人员,但他说他无法获取此类数据,所以他告诉我更改数据

这是我的实际数据

{
  "Details": [{
    "5d4c2c28dcf224127a30457b": {
      "displayName": "ewqeqw"
    },
    "5d4c4699dcf224127a3045e0": {
      "displayName": "mmmmmmmmmm"
    }
  }]
}

我需要以这种格式更改数据

{
  "Details": [{
      "ID": "5d499b0fdcf224127a303d61",
      "displayName": "qweqewq"
    },
    {
      "ID": "5d499b0fdcf224127a303d61",
      "displayName": "qweqewq"
    }
  ]
}

这是我的代码:

var group = Spark.getData().group;
var API = Spark.getGameDataService();
var all1 = new Array();
var entry = API.getItem("playerFriends", Spark.getPlayer().getPlayerId());
var friendsList = {};
if (entry.error()) {
  Spark.setScriptError("ERROR", error);
  Spark.exit();
} else {
  var data = entry.document().getData();
  if (group === "all") {
    for (var friendOBJ in data) {
      //Set details of player ID and display name in new friendsList 
      object
      friendsList[friendOBJ] = {};
      friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
      friendsList[friendOBJ].playerId = data[friendOBJ].playerId;


    }
    all1.push(friendsList);
  } else {
    for (var friendOBJ in data) {
      if (data[friendOBJ].group === group && data[friendOBJ].status ===
        "accepted") {
        friendsList[friendOBJ] = {};
        friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
      }
    }
  }
  Spark.setScriptData("Details", all1);
4

2 回答 2

0

你能不能只做一个函数来将数据转换成所需的形状?像这样的东西应该工作:

function formatData(details) {
  var formattedDetails = [];
  for (var id in details) {
    formattedDetails.push({
      ID: id,
      displayName: details[id].displayName
    });
  }
  return formattedDetails;
}

var data = {
  "Details": [
    {
      "5d4c2c28dcf224127a30457b": {
        "displayName": "ewqeqw"
      },
      "5d4c4699dcf224127a3045e0": {
        "displayName": "mmmmmmmmmm"
      }
    }
  ]
};

var formattedData = formatData(data.Details[0])

于 2019-08-08T19:32:10.507 回答
0

这是你想要的输出

{
  "Details": [{
      "ID": "5d499b0fdcf224127a303d61",
      "displayName": "qweqewq"
    }
 }

这是我的代码,我用注释解释每一行

        var count = 0;
        var tmp = { AcceptedFriendList: []};         //make object and inside empty array                           
        for (var friendOBJ in data) {  // retrieving data
                 if(data[friendOBJ].status === "accepted"){ // your condition
            var tempObj = {"displayName" :"","playerid": ""}; //this is format you want
            tempObj.displayName = data[friendOBJ].displayName; // putting data in spicify format object

            tempObj.playerid =  data[friendOBJ].ID;

            tmp.AcceptedFriendList[count] = tempObj; //assign object back to array

            count++; // iterate it so the next data come further.
        }}
于 2019-11-04T10:12:58.583 回答