javascript - 如何将特定的 JSON 数据放入表中
问题描述
我是一个完全的初学者,所以我有点想把头撞在墙上试图弄清楚这一点。
基本上,下面的代码显示来自 url 的 json 数据并将其显示在表格中。目前,对象中的所有 12 个键都显示在表中。
我想知道的是我将如何只显示表格中的一些键。例如,我将如何构建一个只显示空头、多头、价格和数量的表格。
我希望这是有道理的,在此先感谢
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Using Coincap.io API</title>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container-fluid fill-page">
<div class="row justify-content-center align-items-center">
<div class="col-10">
<div class="waitingDiv text-center">loading...</div>
<table class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-dark"></thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
<script>
$(document).ready(function() {
$.ajax({
url: "https://coincap.io/front",
type: "GET",
dataType: "json"
}).done(function(data, textStatus, jqxhr) {
//only look at first 25 results...
data = data.slice(0, 10);
$.each(data, function(index, value) {
if (index == 0) {
$("thead").append("<tr id='tr-header'> ");
$.each(Object.keys(data[index]), function(propertyName, value){
$("#tr-header").append("<th>" + value + "</th>");
});
$("thead").append("</tr>");
}
$("tbody").append("<tr id='tr-" + index + "'> ");
$.each(data[index], function(propertyPosition, value){
$("#tr-" + index).append(
"<td>" + data[index][propertyPosition] + "</td>"
);
});
$("tbody").append("</tr>");
});
$('.waitingDiv').hide();
}).fail(function(jqxhr, textStatus, errorThrown){
console.log("failed");
});
});
<script>
解决方案
您可以检查 propertyName 是否在要显示的键数组中。
var keys_to_show = ["short", "long", "price", "volume"];
$.each(Object.keys(data[index]), function(propertyName, value) {
if (keys_to_show.includes(propertyName)) {
$("#tr-header").append("<th>" + value + "</th>");
}
});
推荐阅读
- python-3.x - Docusign Webhooks 响应
- rss - Typo3 8.7 将插件内容导出为 RSS 提要
- node.js - 如何使用节点 js 在 aws neptune db 中保存数据?
- python - 字典中的元组列表
- c++ - ld 找不到 -latomic 或 -lstdc++
- ruby-on-rails - 获取 TypeError - 尝试保存时没有将 Symbol 隐式转换为 Integer
- java - Java:日历时区问题
- r - 如何更改 R 中 geom_table() 中列标题的颜色?
- python - 动态声明 kivy MDDataTable 返回 NoneType
- arrays - 错误:对象作为 React 子级无效(找到:带键的对象。如果您要渲染子级集合,请改用数组