如何通过一系列对象JavaScript循环并将其放入表格?

问题描述 投票:0回答:1
<body> <h1 id="header"></h1> <table id="table1"> <thead></thead> <tbody></tbody> </table> <script src="src/script.js"></script> </body>

这是我的JS代码

const data = [ { type: "NS", records: [ "d.u10.twtrdns.net", "a.r10.twtrdns.net", "a.u10.twtrdns.net", "b.r10.twtrdns.net", "b.u10.twtrdns.net", "c.r10.twtrdns.net", "c.u10.twtrdns.net", "d.r10.twtrdns.net", ], }, ] $(function () { const thead = $("#table1 thead") const tbody = $("#table1 tbody") let tr = $("<tr />") $.each(Object.keys(data[0]), function (_, key) { tr.append("<th>" + key + "</th>") }) tr.appendTo(thead) $.each(data, function (_, obj) { tr = $("<tr />") $.each(obj, function (_, text) { tr.append("<td>" + text + "</td>") }) tr.appendTo(tbody) }) })
我想要这样的循环结果


    

$(function () { const thead = $("#table1 thead"); const tbody = $("#table1 tbody"); // Here you can table headers let tr = $("<tr />"); tr.append("<th>Type</th><th>Record</th>"); tr.appendTo(thead); // and append here to thead // then loop through the data and records which is inside of data to show in each rows. // This one for data loop, it will adapt with multiple types, if it is comes $.each(data, function (_, obj) { // This one for to loop the records inside the data to show reach rows $.each(obj.records, function (_, record) { // here need to create to new row for reach loop item let tr = $("<tr />"); tr.append("<td>" + obj.type + "</td>"); tr.append("<td>" + record + "</td>"); tr.appendTo(tbody); // and then just append here to the body }); }); }); // Hope this well work for you i want a loop result like this

javascript html arrays javascript-objects foreach-object
1个回答
0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.