【问题标题】:How to iterate over an object containing arrays in JavaScript?如何在 JavaScript 中迭代包含数组的对象?
【发布时间】:2018-02-14 09:00:20
【问题描述】:

我有以下 JSON 结构 (一个包含数组的数组,其中每个数组都包含一个 dict 元素) 我从基于函数的视图接收到,我想遍历所有元素并丢弃那些是带有空字典的数组。

data.table_values = [[{'id': 1021972,'Aging_Un_investigated_Issue': '0.94', 
'User': 'John P.', 'Open_date':'2017-08-04 01:34:18','End_date':'2017-09-05 00:29:01', 
'Ticket_status':'Transferred'},{'id': 1036722, 'Aging_Un_investigated_Issue': '0.01', 
'User': 'John P.', 'Open_date':'2017-09-01 00:34:18',
'End_date':'', 'Ticket_status':'Researching'},{'id': 1015621, 
'Aging_Un_investigated_Issue': '0.11', 'User': 'John D.','Open_date':'2017-01-01 00:00:18',
'End_date':'2017-09-01 20:20:57','Ticket_status':'Closed'}],
[{}],
[{}],
[{'id': 1045971,'Aging_Un_investigated_Issue': '0.23', 
'User': 'John C.', 'Open_date':'2016-05-01 02:32:18','End_date':'2017-09-05 12:29:01', 
'Ticket_status':'Transferred'},{'id': 1035522, 'Aging_Un_investigated_Issue': '0.02', 
'User': 'John C.', 'Open_date':'2015-08-01 00:34:18',
'End_date':'', 'Ticket_status':'Researching'},{'id': 1223621, 
'Aging_Un_investigated_Issue': '0.11', 'User': 'John C.','Open_date':'2016-01-01 00:00:18',
'End_date':'2017-09-02 21:20:57','Ticket_status':'Closed'}]]

我知道如何遍历一个数组元素的所有值,但我不知道如何遍历所有数组的所有值。

//iterate through all the values of one array element 

<script>
    //select the first list element
   //data.table_values is the variable that receives the JSON 
    var table_values = data.table_values[0]
    setTable()

    function setTable(){
    var tbody = $('#reservations tbody'),
    //iterate through the elements of list 0
    props = ["id", "User", "Open_date", "Ticket_status", "End_date"];
    $.each(table_values, function(i, value) {
        var tr = $('<tr>');
        $.each(props, function(i, prop) {
            $('<td>').html(value[prop]).appendTo(tr);
        });
        tbody.append(tr);
    });

    $(document).ready(function(){
    $('#reservations').DataTable();
    });
  }
</script>

<html>
<table id="reservations" style="width:100%">
<thead>
<tr>
   <th>ID</th>
   <th>User</th>
   <th>Open Date</th>
   <th>Ticket Status</th>
   <th>End Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</html>

如何遍历所有数组并丢弃那些包含空字典的数组?

请随意使用我准备的JS Fiddle,这样您就可以进行一些测试。

【问题讨论】:

  • empty dicts - 这是什么意思?
  • 没有元素,只是一个没有元素的{}

标签: javascript jquery arrays json


【解决方案1】:
  1. Flatten your Array of records
  2. 过滤掉任何没有“id”的元素。

我修改了你的小提琴,添加了mapfilter 语句来完成1和2:http://jsfiddle.net/8a6858b6/1/

扁平化是一种足够的策略,还是您试图保留表数据的数组结构?

【讨论】:

  • 对数组记录进行展平可以达到我想要的效果。
  • 我实施了您的解决方案,但没有收到任何数据。
【解决方案2】:

您想遍历 data.table_values 数组并测试每个元素以查看它是否为空 - 如果是,则跳过迭代。

var data = {}; // Assuming that you have data declared before - 
               // I just need this one here to make the snippet work
data.table_values = [
[{
	'id': 1021972,
	'Aging_Un_investigated_Issue': '0.94',
	'User': 'John P.',
	'Open_date': '2017-08-04 01:34:18',
	'End_date': '2017-09-05 00:29:01',
	'Ticket_status': 'Transferred'
}, {
	'id': 1036722,
	'Aging_Un_investigated_Issue': '0.01',
	'User': 'John P.',
	'Open_date': '2017-09-01 00:34:18',
	'End_date': '',
	'Ticket_status': 'Researching'
}, {
	'id': 1015621,
	'Aging_Un_investigated_Issue': '0.11',
	'User': 'John D.',
	'Open_date': '2017-01-01 00:00:18',
	'End_date': '2017-09-01 20:20:57',
	'Ticket_status': 'Closed'
}], [{}], [{}], [{
	'id': 1045971,
	'Aging_Un_investigated_Issue': '0.23',
	'User': 'John C.',
	'Open_date': '2016-05-01 02:32:18',
	'End_date': '2017-09-05 12:29:01',
	'Ticket_status': 'Transferred'
}, {
	'id': 1035522,
	'Aging_Un_investigated_Issue': '0.02',
	'User': 'John C.',
	'Open_date': '2015-08-01 00:34:18',
	'End_date': '',
	'Ticket_status': 'Researching'
}, {
	'id': 1223621,
	'Aging_Un_investigated_Issue': '0.11',
	'User': 'John C.',
	'Open_date': '2016-01-01 00:00:18',
	'End_date': '2017-09-02 21:20:57',
	'Ticket_status': 'Closed'
}]
];

for(table_values of data.table_values) {
    if( table_values.length == 0 ) continue;
    setTable();
}

function setTable(){
    var tbody = $('#reservations').find('tbody'),
    //iterate through the elements of list 0
    props = ["id", "User", "Open_date", "Ticket_status", "End_date"];
    $.each(table_values, function(i, value) {
       var tr = $('<tr>');
        $.each(props, function(i, prop) {
            $('<td>').html(value[prop]).appendTo(tr);
        });
        tbody.append(tr);
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="reservations" style="width:100%">
<thead>
<tr>
   <th>ID</th>
   <th>User</th>
   <th>Open Date</th>
   <th>Ticket Status</th>
   <th>End Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

【讨论】:

  • 你不应该这样做 == {} - 在 JavaScript 中 {} 每次都是一个新对象,所以它总是会失败。由于table_values 是一个数组,一个更简单的解决方案是测试它的长度:table_values.length &gt; 0。我已提议对问题进行修改以反映这一点。
  • 那么,我们可以做些什么来避免使用== {}
  • @AlejandroBautistaRamos @Aydin 如果你需要做== {},你可以先在两边使用JSON.stringify,这是一种快速而肮脏的方法。有关更优雅的方式,请参阅此 q/a:stackoverflow.com/questions/679915
  • 在做涉及 ids 的 jQuery 选择器时,首先做 id 选择器总是更有效,然后在结果上调用 .find()$('#reservations').find('tbody') 而不是 $('#reservations tbody'),因为对于 ids jQuery 只是使用原生的 getElementById 方法。
  • 另外,没有理由在 for 循环中使用 setTable() 函数 - 只需修复它即可。我只是想指出如何遍历数组,而不是提供整体代码改进审查:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 2019-02-27
相关资源
最近更新 更多