Search code examples
javascriptjqueryhtml-tableappendgetjson

Split up JSON Object into multiple <td>


I'm currently trying to create a Character Ranking system similar to this one.

With the official API I am able to append all the data via $.getJSON and the URL into a table.

So far I'm showing 20 characters and got all the character data inside multiple table rows (one for each character), but haven't figured out how I can split up the character object into multiple <td>, so that I have better control of addressing them via CSS.

Here's the code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.getJSON("http://api.pathofexile.com/ladders/Standard?callback=?", function (result) {

                    $("#tdPlayer").append("<td>" + result["total"] + "</td>" + "<br/>");

                    $("#tdSince").append("<td>" + result["cached_since"] + "</td>" + "<br/>");

                    $.each(result["entries"], function (index, value) {
                        $("#tdRanking").append("<tr>" + "<td>" + JSON.stringify(index, null, '\t') + ": " + JSON.stringify(value, null, '\t') + "</td>" + "</tr>" + "<br/>");

                    });
                });
            });
        });

    </script>
</head>

<body>

    <button>Anzeige der Top 20 Spieler in der Incursion Liga</button>

    <div>
        <table>
            <tr>
                <td id="tdPlayer">Anzahl der Spieler:</td>
                <td id="tdSince">Suchbeginn: </td>
            </tr>
            <tr>
                <td colspan="2" id="tdRanking">Spieler: (max. 20 angezeigt)</td>
            </tr>
        </table>
    </div>

</body>

</html>

An example of how the currently appended character objects look like inside the table.

The whole JSON object where I append my data from can be found here.


Solution

  • You can access the character properties within your $.each function using the non-stringified value variable. For example, to access the character name, use value.character.name

    $("#tdRanking").append("<tr><td>" + JSON.stringify(index, null, '\t') + '<td>' + value.character.name + "</td></tr>");
    

    I've added an example on codepen

    Please note that i am not using ajax to retrieve the data as your data source is not being served over https://