首页 > 解决方案 > 如何将特定的 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>

标签: javascriptjqueryhtmljson

解决方案


您可以检查 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>");
    }
});

推荐阅读