HTML表使用JavaScript跳过分组中的重复行

时间:2018-08-10 14:39:59

标签: javascript ajax grouping

我正在使用AJAX和PHP从数据库中获取多个数据。在AJAX成功之后,我将结果数据分组,如下图所示,其中我希望每个组一个textarea字段。

我正在尝试以下脚本

function getResult(id = null) {
  if (id) {
    $.ajax({
      url: 'fetch.php',
      type: 'post',
      data: {id: id},
      dataType: 'json',
      success: function(response) { 
        var lastCategory = null;
        response.result.forEach(function(element) {
          console.log(element);
          var category = element.category;
          var names = element.name;
          var Result = element.result;
          var note = element.note;
          if (lastCategory != category) {
            $('table tr').length;
            html = '<tr>';
            html += '<td><p>'+category+'</p></td>';
            html += '</tr>';
            $('table').append(html);
            lastCategory = category;
          }
          $('table tr').length;
          html = '<tr>';
          html += '<td><p>' + names + '</p></td>';
          html += '<td><p>' + Result + '</p></td>';
          html += '</tr>';
          $('table').append(html);
          $('table tr').length;
          html = '<tr>';
          html += '<td><textarea placeholder="textarea...">' + note + '</textarea></td>';
          html += '</tr>';
          $('table').append(html);
        });
      }
    });
  } else {
    alert('error');
  }
}

但是它给出了以下输出:

enter image description here

这是所需的输出:

enter image description here

1 个答案:

答案 0 :(得分:3)

在这一点上,我很可能会将您的数据转换为所需的格式。在这种情况下,您的response.resultcategory分组。我模拟了一个非常简单的示例,说明如何通过.forEach()循环来完成此操作,但是还有其他选择,例如使用.groupBy()函数here。 (即var cats = groupBy(response.result, 'category')

现在,这可以更轻松地将类别与实际元素分开。请参见下面的代码:

var response = {
  result: [
    {category: 'Team A', name: 'Jema', result: 43},
    {category: 'Team B', name: 'Deno', result: 34},
    {category: 'Team B', name: 'Niob', result: 56},
    {category: 'Team B', name: 'Skion', result: 49},
  ],
};

var cats = {};

response.result.forEach(function(element) {
  cats[element.category] = cats[element.category] || [];
  cats[element.category].push(element);
});

Object.keys(cats).forEach(function(category) {
  let html = '';
  
  // Append the category header
  html = '<tr>';
  html += '<td><p>'+category+'</p></td>';
  html += '</tr>';
  $('table').append(html);
  
  // Loop through the results for this category
  cats[category].forEach(function(element) {
    var names = element.name;
    var result = element.result;
    html = '<tr>';
    html += '<td><p>' + names + '</p></td>';
    html += '<td><p>' + result + '</p></td>';
    html += '</tr>';
    $('table').append(html);
  });
  
  // Append the textarea at the end of the results
  html = '<tr>';
  html += '<td><textarea placeholder="textarea..."></textarea></td>';
  html += '</tr>';
  $('table').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>