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

How do I get DataTables to read nested objects in an array?

我正在尝试获取 DataTables to read an array containing nested objects, with the data coming from another JSON file. This is part of a freeCodeCamp 项目。

使用 console.log(dataSet) 并手动创建一个数组工作得很好,但我似乎无法让 DataTables 从数据集数组输出数据,该数组已从 Twitch.tv API.

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" }
    ]
});
});

您需要确保 dataSet 中已填充了 API 中的所有数据。有一个计数器并将其与 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