简体   繁体   English

jQuery-遍历返回的JSON数组和分组

[英]jQuery - Iterating over returned JSON array and grouping

So I have a JSON array being returned in a getJSON .done function, which is all working great. 因此,我在getJSON .done函数中返回了一个JSON数组,所有这些都很好用。 The array returns in a similar format to below: 数组以类似于以下格式返回:

results
   |___date
   |___name
   |___score

thing is I might get a set of results like: 问题是我可能会得到如下结果:

01.01.2014
Joe Bloggs
25
01.01.2014
Jim Jones
50
02.01.2014
Alice Smith
33
01.01.2014
Eve Harris
40

What I'd like to do is tabulate the results grouped by date. 我想做的是将按日期分组的结果制成表格。 So having a 'tr' for the date followed by the results for that date, like: 因此,在日期前加上“ tr”,然后是该日期的结果,例如:

01.01.2014
Joe Bloggs    25
Jim Jones     50
Eve Harris    40
02.01.2014
Alice Smith   33

I'm currently populating the table using the following code: 我目前正在使用以下代码填充表格:

    $.each(rows, function() {
            var table = $('#table-results');
            var matchDate = this.date;
            var row = $('<tr>');
            var name = $('<td>').html(this.name);
            var score = $('<td>').html('<strong>' + this.score + '</strong>');
            row.append(matchDate, name, score);
            table.append(row);
    });

How can I add another $.each loop which will loop over each date in the result set? 如何添加另一个$ .each循环,该循环将遍历结果集中的每个日期?

http://jsfiddle.net/fwpzr/1/ http://jsfiddle.net/fwpzr/1/

Group data first, then dump to table; 首先将数据分组,然后转储到表中; does not assume sorted data. 不假设排序的数据。

// Assumption: JSON data is in "rows"
var data = {};
var dates = [];
$.each(rows, function () {
    if (typeof data[this.date] == "undefined")
    {
        data[this.date] = [];
    }
    data[this.date].push(this);
    if (dates.indexOf(this.date) == -1)
    {
        dates.push(this.date);
    }
});
dates = dates.sort();

var table = $('#table-results');
$.each(dates, function () {
    table.append(
        $("<tr>").append(
            $("<th>").attr("colspan", "2")
                     .html(this)
        )
    );

    data[this] = data[this].sort(function (a, b) {
        return a.name > b.name;
    });

    $.each(data[this], function () {
        table.append(
            $("<tr>").append(
                $("<td>").html(this.name)
            ).append(
                $("<th>").html(this.score)
            )
        );
    });
});

Store all of your records in a hash (byDate) first. 首先将所有记录存储在哈希中(byDate)。 And then enumerate over that. 然后列举一下。 See this JSFiddle 看到这个JSFiddle

var rows = [
    {date: "01.01.2014", name: "Joe Bloggs", score: "25"},
    {date: "01.01.2014", name: "Jim Jones", score: "50"},
    {date: "02.01.2014", name: "Alice Smith", score: "33"},
    {date: "01.01.2014", name: "Eve Harris", score: "40"},
];

var byDate = {};
$.each(rows, function() {
  var r = byDate[this.date] || (byDate[this.date] = []);
  r.push(this);
});
var table = $('#table-results');
for (var d in byDate) {
  table.append($('<tr><td>'+d+'</td></tr>'));
  $.each(byDate[d], function() {
    var row = $('<tr>');
    var name = $('<td>').html(this.name);
    var score = $('<td>').html('<strong>' + this.score + '</strong>');
    row.append(name, score);
    table.append(row);
  });
}
        $.each(rows, function() {
            var table = $('#table-results');
            var matchDate = this.date;
            var headerRow = $('#header_for_' + matchDate.replace(/\./g, ''));
            if(headerRow.length === 0) {
                headerRow = $('<tr>');
                $(headerRow).attr('id', 'header_for_' + matchDate.replace(/\./g, ''));
                headerRow.append(matchDate);
                table.append(headerRow);
            }
            var dataRow = $('<tr>');
            $(dataRow).attr('data-date', matchDate);
            var name = $('<td>').html(this.name);
            var score = $('<td>').html('<strong>' + this.score + '</strong>');
            dataRow.append(name, score);
            var lastDataRowThisDate = $('tr[data-date="' + matchDate + '"]').last();
            if(lastDataRowThisDate.length === 0) {
                lastDataRowThisDate = headerRow;
            }
            dataRow.insertAfter(lastDataRowThisDate);
    }); 

You should be able to sort the table, like so: 您应该能够对表格进行排序,如下所示:

 <table id="mytable">
   <tbody>
     <tr>
       <td>02.01.2014</td>
       <td>hello</td>
     </tr>
     <tr>
       <td>02.01.2014</td>
       <td>hello2</td>
     </tr>
     <tr>
       <td>01.01.2014</td>
       <td>hello</td>
     </tr>
   </tbody>
  </table>

function sortTable(){
  var rows = $('#mytable tbody  tr').get();

  rows.sort(function(a, b) {

  var A = $(a).children('td').eq(0).text().toUpperCase();
  var B = $(b).children('td').eq(0).text().toUpperCase();

  if(A < B) {
    return -1;
  }

  if(A > B) {
    return 1;
  }

  return 0;

  });

  $.each(rows, function(index, row) {
    $('#mytable').children('tbody').append(row);
  });
}
sortTable();

Even if dates are unordered, create a new empty json object, do a loop over the original json, at each iteration add to the new json object indexed by date. 即使日期是无序的,也要创建一个新的空json对象,在原始json上循环,在每次迭代时,将其添加到按日期索引的新json对象。

The final object would be like: 最终对象将是:

{
'01.01.2014': [
        {'Joe Bloggs',25},
        {'Jim Jones',50},
        {'Eve Harris',40}
    ]
    /* and so on */
}

Then you can format this new json object easily. 然后,您可以轻松格式化此新的json对象。

Ok ? 好 ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM