Я пытаюсь получить DataTables для чтения массива, содержащего вложенные объекты, с данными, поступающими из другого файла JSON.Это часть проекта freeCodeCamp .
Использование console.log(dataSet)
и создание массива вручную работает отлично, но я не могу заставить DataTables выводить данные из массива dataSet, которыйполучил данные из API Twitch.tv.
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" }
]
});
});