如何对以 JSON 格式返回的数据进行分组并返回

How can I group data returned in JSON format and return it?

本文关键字:返回 数据 JSON 格式      更新时间:2023-09-26

我有一个格式为:

[
    {"ID":153,"CircuitID":53,"StartTime":"2014-11-12 12:45:00","EventFormatID":224,"TotalPlaces":8,"BookedPlaces":0,"ProvisionalPlaces":0},
    {"ID":161,"CircuitID":53,"StartTime":"2014-11-12 17:15:00","EventFormatID":224,"TotalPlaces":0,"BookedPlaces":0,"ProvisionalPlaces":0},
    {"ID":734,"CircuitID":53,"StartTime":"2014-11-12 18:30:00","EventFormatID":231,"TotalPlaces":14,"BookedPlaces":0,"ProvisionalPlaces":0}
]

代替事件格式 ID 和电路 ID,我将返回名称

我需要做的是按事件格式 ID 对结果进行分组,并按以下格式返回结果:

Event 224 : 12:45 (8 places available), 17:15 (0 places available)
Event 231 : 18:30 (14 places available)

我似乎无法弄清楚如何循环访问数据,按事件格式 ID 对其进行分组以所需的格式呈现它!

谢谢

您可以使用任何其他库吗? 我会使用 lo-dash,这将使这相对简单:

var grouped = _.groupBy(data, "EventFormatID");
_(grouped).forEach(function (group, key) {
    console.log("Event:" + key);
    _(group).forEach(function (course) {
        console.log(course.StartTime + " (" + course.TotalPlaces + " places available)");
    });
});

显然,上面的示例会记录到控制台,但是更改以构建所需的任何字符串或对象会相当简单。

使用 lodash/underscore,甚至使用 ES5 数组和对象方法,这更容易,但既然您询问了纯 JS:

var data = {}, results = [], i, j, id, time, obj, evts; // obj is your object above
for (i=0; i<obj.length; i++) {
  id = obj[i].EventFormatID;
  time = obj[i].StartTime; // you can simplify to get just the time, not the datetime, if you prefer
  data[id] = data[id] || [];
  data[id].push({"time":time,"places":obj[i].TotalPlaces});
}
// now you have a proper data structure, just print it out
for (i in data) {
  if (data.hasOwnProperty(i)) {
    // just show the output properly formatted
    evts = [];
    for (j=0;i<data[i].length;j++) {
       evts.push(data[i][j].time+" ("+data[i][j].places+" places available)");
    }
    results.push("Event "+i+" : "+evts.join(","));
  }
}

ES5 让这一切变得如此简单

var data = {}, results = [], obj; // obj is your object above
obj.forEach(function(val,i) {
  data[val.EventFormatID] = data[val.EventFormatID] || [];
  data[val.EventFormatID].push({"time":val.StartTime,"places":val.TotalPlaces});
});
// now you have a proper data structure, just print it out
Object.keys(data).forEach(function(key) {
  var value = data[key], evts = [];
  value.forEach(function(elm) {
     evts.push(elm.time+" ("+elm.places+" places available)");
  });
  results.push("Event "+key+" : "+evts.join(","));
});

而洛达什则更容易。

请看一下:

http://jsfiddle.net/m260n5ud/

.html

<div id="contentDiv"></div>

.js

function tidyUp(jsonArray) {
    var myObject = {};
    for (i = 0; i < jsonArray.length; i++) {
        var key = jsonArray[i]['EventFormatID'];
        var time = jsonArray[i]['StartTime'].replace(' ', ':').split(/[- :]/);
        time = time[3] + ":" + time[4];
        var totalPlace = jsonArray[i]['TotalPlaces'];
        if (myObject[key] == null) {
            myObject[key] = "Event : " + key + " : " + time + " ( " + totalPlace + " places available)";
        } else {
            myObject[key] += ", " + time + " ( " + totalPlace + " places available)";
        }
    }
    console.log(myObject);
    for (var k in myObject) {
        document.getElementById('contentDiv').innerHTML += myObject[k] + "<br/>";
    }
}