简体   繁体   English

如何从对象数组创建 HTML 表格?

[英]How to create an HTML table from an array of objects?

I need to generate a table from an array of objects.我需要从一组对象生成一个表。

For example, the array is:例如,数组是:

let arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}]

And the HTML output should be: HTML 输出应该是:

Name姓名 Score分数
Player1播放器1 10 10
PLayer2播放器2 7 7
Player3播放器3 3 3

I could not think of a way to achieve this through vanilla JS.我想不出通过 vanilla JS 实现这一目标的方法。 Also, after the table is created, how will I apply CSS to it?另外,创建表格后,我将如何对其应用 CSS?

Any help would be appreciated.任何帮助,将不胜感激。

You can loop through the array and for each element add a row to a newly forged table that will be added to the document at the end.您可以循环遍历数组,并为每个元素添加一行到新伪造的表中,该表将在最后添加到文档中。

This is a demo:这是一个演示:

 let players = [ {name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3} ]; const newTable = document.createElement("table"); newTable.innerHTML = "<thead><th>Player</th><th>Score</th></thead>"; for(player of players){ const newRow = document.createElement("tr"); const tdPlayer = document.createElement("td"); const tdScore = document.createElement("td"); tdPlayer.textContent = player.name; tdScore.textContent = player.score; newRow.appendChild(tdPlayer); newRow.appendChild(tdScore); newTable.appendChild(newRow); } const target = document.getElementById('target'); target.appendChild(newTable);
 table{ border: solid 1px black; } table td{ border: solid 1px black; }
 <div id="target"> </div>

You can use something like你可以使用类似的东西

<body>
<div class="main-container">
    <table>
        <thead>
            <tr>
                <th>player</th>
                <th>score</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script>
    const data = [{ name: 'Player 1', score: 10 },
    { name: 'Player 2', score: 7 },
    { name: 'Player 3', score: 3 }]

    const table = document.querySelector('tbody')
    data.forEach((item) => {
        table.innerHTML = table.innerHTML + `<tr>
                <td>${item.name}</td>
                <td>${item.score}</td>
            </tr>`
    })
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM