javascript - Jquery数据表过滤重复行

标签 javascript jquery html ajax datatables

$(document).ready(function () {
  var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';

  var table = $('#example').DataTable({
    'processing': true,
    'serverSide': true,
    'paging': false,
    'bFilter': false,
    'ajax': {
      type: 'POST',
      'url': url,
      'data': function (d) {
        return JSON.stringify( d );
      }
    }
  });
  table.column( 3 ).data().unique();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>First name</th>
            <th>Last name</th>
            <th>Position</th>
            <th>Office</th>
        </tr>
    </thead>
</table>

我正在尝试使用datatable unique function但我无法执行它。实际上我想删除我正在使用动态ajax数据的重复数据。

table
    .column( 3 )
    .data()
    .unique();

就像在这个例子中,我想过滤掉城市,请告诉我我做错了什么,还有其他方法吗,我在 stackoverflow 中找不到任何其他答案,或者可能无法理解。我使用的是1.10.9版本

最佳答案

注意unique的实际用途:

Create a new API instance containing only the unique items from a the elements in an instance's result set.

Unique 返回一组经过筛选的唯一项目,它不会筛选表中显示的行。由于您想显示删除重复数据的行,我建议您在 dataSrc 回调中过滤掉重复数据。您没有提供有关 JSON 的详细信息,但这里是一个包含“规范”JSON 数据集之一的示例,其中重复的办公室被过滤掉。它只是在返回的 data 数组上使用 javascripts Array.filter :

var table = $('#example').DataTable({
  ajax: {
    url: 'https://api.myjson.com/bins/avxod',
    dataSrc: function(json) {
       var offices = [];
       return json.data.filter(function(item) {
         if (!~offices.indexOf(item.office)) {
           offices.push(item.office);
           return item;
         }
       })
    }
  },
  columns: [
    { data: 'name' },
    { data: 'position' },    
    { data: 'office' },        
    { data: 'salary' }
  ]
})  

演示 -> http://jsfiddle.net/cbcqdj7h/

关于javascript - Jquery数据表过滤重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45075982/

相关文章:

javascript - PyCharm:src 目录下的 JavaScript 文件被锁定

javascript - Rails 合并表单字段

javascript - knockout 嵌套 foreach 模板未按预期工作

html - CSS 区分 hover on element 和 it's::before 伪元素

javascript - 生成动态 HTML 时正确转义字符

javascript - 第二次和第三次点击时的事件

jquery - 如何根据滚动距离更改标题中的 Logo ?

html - 防止 Googlebot 频繁地重新索引某些页面

jquery - 将元素内容附加到另一个元素的内容

javascript - JQuery window.resize 不断地在我的 HTML 前面添加不止一次