如何让DataTables读取数组中的嵌套对象?

时间:2018-05-27 11:59:02

标签: javascript arrays datatables javascript-objects twitch

我试图让DataTables读取包含嵌套对象的数组,数据来自另一个JSON文件。这是freeCodeCamp项目的一部分。

使用console.log(dataSet)并手动创建数组非常合适,但我似乎无法从DataTables输出已从Twitch.tv API推送数据的dataSet数组中的数据。

HTML:

    <head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Twitch.tv App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css"
/>
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script src="main.js"></script>
    </head>

    <body>
<table id="table" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>Channel</th>
            <th>Status</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

    </body>

JS:

    $(document).ready(function () {
var usernames = ["tooshi", "ESL_SC2", "OgamingSC2", "cretetion", "dotademon", "jakenbakelive", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var dataSet = [];
usernames.forEach(function (username) {
    var apiUrl = "https://wind-bow.glitch.me/twitch-api/streams/"
    apiUrl += username;

    $.getJSON(apiUrl, function (json) {
        var channelUrl = "https://www.twitch.tv/";
        channelUrl += username;
        if (json.stream === null) {
            var status = "Offline";
            dataSet.push({ username, channelUrl, status });
        } else {
            status = "Online";
            var description = json.stream.channel.status;
            dataSet.push({ username, channelUrl, status, description });
        };

    });

});
console.log(dataSet);
$('#table').DataTable({
    data: dataSet,
    columns: [
        { data: "username" },
        { data: "status" },
        { data: "description" }
    ]
});
});

1 个答案:

答案 0 :(得分:0)

您需要确保已使用API​​中的所有数据填充dataSet。拥有一个计数器并将其与usernames.length进行比较是一种方法。

counter++;
  if (counter === usernames.length) {
    $('#table').show();
    $('#table').DataTable({
      data: dataSet,
      columns: [{
          data: "username"
        },
        {
          data: "status"
        },
        {
          data: "description"
        }
      ]
    });
  }

另外,请确保dataSet上的推送数据具有相同的长度,在description上分配空白即可。

if (json.stream === null) {
        status = "Offline";
        description = '';
        dataSet.push({
          username,
          channelUrl,
          status,
          description
        });
      }

JSFiddle