jQuery如何在DataTables中实现嵌套的$ .each()

时间:2021-07-30 00:21:10

I get Json data from server in order to display information by using DataTables.

我从服务器获取Json数据,以便使用DataTables显示信息。

In this json, there are rows, where in a column there may exist more than one value, so it's a multidimensional array as follows (I show just an excerpt of the array):

在这个json中,有一些行,在一列中可能存在多个值,所以它是一个多维数组,如下所示(我只显示了数组的摘录):

{
    "info_table": [
        {
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [
                {
                    "name": "CARL SMITH"
                }
            ],
            "assistants": [
                {
                    "name": "YULIA SMIRNOVA"
                }
            ]
        }
    ]
}

The DataTable works fine so far:

到目前为止,DataTable工作正常:

$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
$.each(response.info_table,function(i,item){
  $('#notes_table').find('tbody').append('<tr><td>'+item.researchers+'</td><td>'+item.date+'</td></tr>');
});

The date column values are displayed fine, however, for the researcherscolumn only [object Object] is displayed. If I try to use a nested $.each() as follows:

日期列值显示正常,但是,对于研究人员列,仅显示[对象对象]。如果我尝试使用嵌套的$ .each(),如下所示:

$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
 $.each(response.info_table,function(i,item){
   $.each(item.researchers, function(j,item2){
    $('#notes_table').find('tbody').append('<td>'+item2.name+'</td>');
   });
 $('#notes_table').find('tbody').append('<td>'+item.date+'</td>');
});

I don't get anything, I just see a DataTables message saying Sorry, no results found.

我没有得到任何东西,我只是看到一条DataTables消息说抱歉,没有找到结果。

What am I missing? Any ideas?

我错过了什么?有任何想法吗?

Solution

Thanks to BLSully:

感谢BLSully:

The working code looks as follows:

工作代码如下:

  var table = $('#table_id').DataTable({
    columns: [{
      data: 'researchers[, ].name',
      title: 'Researchers'
    }, {
      data: 'date',
      title: 'Date'
    }]  
  });

  table.rows.add(data).draw();

And that was it.

就是这样。

2 个解决方案

#1


4  

I'm assuming based on your wording, you're using datatables. Given that, I'm going to provide an alternate example of handling databinding to your table that utilizes the design of the plugin rather than manual DOM manipulation. So.. this isn't exactly an answer to the question, but rather a suggestion of the proper way of doing what you're trying to achieve (given the context you've provided. Depending on how your retrieving your data, there may be some slight changes)

我假设根据你的措辞,你正在使用数据表。鉴于此,我将提供一个处理数据绑定到表的替代示例,该数据绑定利用插件的设计而不是手动DOM操作。所以..这不是问题的答案,而是建议你正在尝试实现的目标的正确方法(根据你提供的上下文。根据你检索数据的方式,可能会有稍微改变一下)

The correct way to add orthogonal json data to your table is by creating column definitions so the table knows which columns to display your data, along with rules around how it's to be displayed.

将正交json数据添加到表中的正确方法是创建列定义,以便表知道显示数据的列以及有关如何显示数据的规则。

I set up an example based on your data (expanded a bit to explain how to deal with deeply nested objects and arrays). The really relevant bit is the data property on the first column: researchers[, ].name. The syntax of that value instructs datatables to treat the property researchers as an array, and displaying it in a comma-separated fashion. Because the array elements are JavaScript objects, the .name following the square brackets instructs DataTables on which property of the object should be displayed.

我根据您的数据设置了一个示例(扩展了一下以解释如何处理深层嵌套的对象和数组)。真正相关的位是第一列的数据属性:研究人员[,]。name。该值的语法指示数据表将属性研究人员视为数组,并以逗号分隔的方式显示它。因为数组元素是JavaScript对象,所以方括号后面的.name指示DataTables应该显示对象的属性。

http://live.datatables.net/domivewi/1/

http://live.datatables.net/domivewi/1/

var data = [
        {
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [{
                    "name": "CARL SMITH"
            },{
                    "name": "JOHN DOE"
            }],
            "assistants": [
                {
                    "name": "YULIA SMIRNOVA"
                }
            ]
        },{
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [{
                    "name": "FRED FLINSTONE"
            },{
                    "name": "WILMA FLINTSTONE"
            }],
            "assistants": [
                {
                    "name": "BARNEY RUBBLE"
                }
            ]
        }
    ];

  var table = $('#demo').DataTable({
    columns: [{
      //this is the important bit here. See explanation above
      data: 'researchers[, ].name',
      title: 'Researchers'
    }, {
      data: 'date',
      title: 'Date'
    }]  
  });
  
  //this line adds new rows to the table and redraws
  table.rows.add(data).draw();
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}


div.container {
  min-width: 980px;
  margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

    <link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
  <body>
    <table id="demo"></table>
  </body>
</html>

#2


0  

Try This ...

尝试这个 ...

First of all save the json string in javascript array.

首先将json字符串保存在javascript数组中。

Like this ...

喜欢这个 ...

var myArray = Array();

myArray = {
    "info_table": [
        {
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [
                {
                    "name": "CARL SMITH"
                }
            ],
            "assistants": [
                {
                    "name": "YULIA SMIRNOVA"
                }
            ]
        }
    ]
}

// Then Execute like this .. 
$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
 $.each(myArray.info_table,function(i,item){
   for( var i; i < item.researchers.length, i++){
    $('#notes_table').find('tbody').append('<td>'+item.researchers[i].name+'</td>');
   });
 $('#notes_table').find('tbody').append('<td>'+item.date+'</td>');
});

#1


4  

I'm assuming based on your wording, you're using datatables. Given that, I'm going to provide an alternate example of handling databinding to your table that utilizes the design of the plugin rather than manual DOM manipulation. So.. this isn't exactly an answer to the question, but rather a suggestion of the proper way of doing what you're trying to achieve (given the context you've provided. Depending on how your retrieving your data, there may be some slight changes)

我假设根据你的措辞,你正在使用数据表。鉴于此,我将提供一个处理数据绑定到表的替代示例,该数据绑定利用插件的设计而不是手动DOM操作。所以..这不是问题的答案,而是建议你正在尝试实现的目标的正确方法(根据你提供的上下文。根据你检索数据的方式,可能会有稍微改变一下)

The correct way to add orthogonal json data to your table is by creating column definitions so the table knows which columns to display your data, along with rules around how it's to be displayed.

将正交json数据添加到表中的正确方法是创建列定义,以便表知道显示数据的列以及有关如何显示数据的规则。

I set up an example based on your data (expanded a bit to explain how to deal with deeply nested objects and arrays). The really relevant bit is the data property on the first column: researchers[, ].name. The syntax of that value instructs datatables to treat the property researchers as an array, and displaying it in a comma-separated fashion. Because the array elements are JavaScript objects, the .name following the square brackets instructs DataTables on which property of the object should be displayed.

我根据您的数据设置了一个示例(扩展了一下以解释如何处理深层嵌套的对象和数组)。真正相关的位是第一列的数据属性:研究人员[,]。name。该值的语法指示数据表将属性研究人员视为数组,并以逗号分隔的方式显示它。因为数组元素是JavaScript对象,所以方括号后面的.name指示DataTables应该显示对象的属性。

http://live.datatables.net/domivewi/1/

http://live.datatables.net/domivewi/1/

var data = [
        {
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [{
                    "name": "CARL SMITH"
            },{
                    "name": "JOHN DOE"
            }],
            "assistants": [
                {
                    "name": "YULIA SMIRNOVA"
                }
            ]
        },{
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [{
                    "name": "FRED FLINSTONE"
            },{
                    "name": "WILMA FLINTSTONE"
            }],
            "assistants": [
                {
                    "name": "BARNEY RUBBLE"
                }
            ]
        }
    ];

  var table = $('#demo').DataTable({
    columns: [{
      //this is the important bit here. See explanation above
      data: 'researchers[, ].name',
      title: 'Researchers'
    }, {
      data: 'date',
      title: 'Date'
    }]  
  });
  
  //this line adds new rows to the table and redraws
  table.rows.add(data).draw();
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}


div.container {
  min-width: 980px;
  margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

    <link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
  <body>
    <table id="demo"></table>
  </body>
</html>

#2


0  

Try This ...

尝试这个 ...

First of all save the json string in javascript array.

首先将json字符串保存在javascript数组中。

Like this ...

喜欢这个 ...

var myArray = Array();

myArray = {
    "info_table": [
        {
            "date": "2015-01-06",
            "subject": "Some subject or title",
            "type": "article",
            "url": null,
            "pdf": null,
            "notes": null,
            "created_at": "2015-06-26 13:38:53",
            "updated_at": "2015-06-26 13:38:53",
            "institute": "Some Institute name",
            "researchers": [
                {
                    "name": "CARL SMITH"
                }
            ],
            "assistants": [
                {
                    "name": "YULIA SMIRNOVA"
                }
            ]
        }
    ]
}

// Then Execute like this .. 
$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
 $.each(myArray.info_table,function(i,item){
   for( var i; i < item.researchers.length, i++){
    $('#notes_table').find('tbody').append('<td>'+item.researchers[i].name+'</td>');
   });
 $('#notes_table').find('tbody').append('<td>'+item.date+'</td>');
});