从对象数组生成 HTML 表格

我一直在尝试生成一个函数来从对象数组创建 HTML 表。这是需要做成表的数组。


let units = [

    {

        'code': 'COMP2110',

        'title': 'Web Technology', 

        'offering': 'S1'

    },  

    {

        'code': 'COMP2010',

        'title': 'Algorithms and Data Structures', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2150',

        'title': 'Game Design', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2320',

        'title': 'Offensive Security', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2200',

        'title': 'Data Science', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2250',

        'title': 'Data Communications', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2300',

        'title': 'Applied Cryptography', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2000',

        'title': 'Object-Oriented Programming Practices', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2050',

        'title': 'Software Engineering', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2100',

        'title': 'Systems Programming', 

        'offering': 'S2'

    }

]

我尝试过一个功能,但我不知道如何让它工作。我也不知道如何查询该函数。


function unit_table() {

    var totalRows = 3;

    var cellsInRow = 3;


    function drawTable() {

        // get the reference for the body

        var first = document.getElementById('first');


        // creates a <table> element

        var tbl = document.createElement("table");


        // creating rows

        for (var r = 0; r < totalRows; r++) {

            var row = document.createElement("tr");


            // create cells in row

            for (var c = 0; c < cellsInRow; c++) {

                m=0;

                var cell = document.createElement("td");

                var cellText = document.createTextNode(units[n][m]);

                cell.appendChild(cellText);

                row.appendChild(cell);

                m=m+1;

            }           


任何帮助将不胜感激。


www说
浏览 132回答 4
4回答

红颜莎娜

如果是包含对象键的字符串,则它将units[n][m]起作用。mexample units[0]["code"]将返回第一个对象的代码值。填充表可以通过在字符串中动态生成 html 并将table.innerHTML其设置为表来完成。为此,我们使用以下方法迭代键for (let key in object)对于列名称let tableString="<tr>"for(let column in units[0]){&nbsp; tableString+=`<th>${column}</th>`}上面的代码将生成一个像这样的字符串<tr><th>code</th><th>title</th><th>offering</th></tr>对于列数据tableString+="</tr>"units.forEach(element => {&nbsp; &nbsp; tableString+="<tr>"&nbsp; &nbsp; for(let prop in element){&nbsp; &nbsp; &nbsp; tableString+=`<td>${element[prop]}</td>`&nbsp; &nbsp; }&nbsp; &nbsp; tableString+="</tr>"});上面将生成这样的字符串,并且这将重复直到数组末尾&nbsp;<tr>&nbsp; &nbsp;<td>COMP2110</td>&nbsp; &nbsp;<td>Web Technology</td>&nbsp; &nbsp;<td>S1</td>&nbsp; &nbsp;</tr>&nbsp; <tr>...&nbsp; </tr>&nbsp; <tr>...&nbsp; </tr>最后&nbsp;document.querySelector('#tb').innerHTML=tableString;let units = [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2110',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Web Technology',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp;&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2010',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Algorithms and Data Structures',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2150',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Game Design',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2320',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Offensive Security',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2200',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Data Science',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2250',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Data Communications',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2300',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Applied Cryptography',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2000',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Object-Oriented Programming Practices',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2050',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Software Engineering',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2100',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Systems Programming',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; }]let tableString="<tr>"for(let column in units[0]){&nbsp; tableString+=`<th>${column}</th>`}tableString+="</tr>"units.forEach(element => {&nbsp; &nbsp; tableString+="<tr>"&nbsp; &nbsp; for(let prop in element){&nbsp; &nbsp; &nbsp; tableString+=`<td>${element[prop]}</td>`&nbsp; &nbsp; }&nbsp; &nbsp; tableString+="</tr>"});document.querySelector('#tb').innerHTML=tableString;table td {border:1px solid black;}<table id="tb"></table>

暮色呼如

您的代码基本上是正确的,但存在一些结构问题。您在函数内部定义函数会导致一些问题,您没有声明所有变量并且无法正确访问单元。看一下,如果您需要更多帮助,请告诉我。let units = [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2110',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Web Technology',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp;&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2010',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Algorithms and Data Structures',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2150',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Game Design',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2320',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Offensive Security',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S1'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2200',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Data Science',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2250',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Data Communications',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2300',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Applied Cryptography',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2000',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Object-Oriented Programming Practices',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2050',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Software Engineering',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'code': 'COMP2100',&nbsp; &nbsp; &nbsp; &nbsp; 'title': 'Systems Programming',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'offering': 'S2'&nbsp; &nbsp; }]key=['code','title','offering'];console.log(units[1].title);&nbsp; &nbsp; var totalRows = 3;var cellsInRow = 3;var n=0,m=0;&nbsp; &nbsp; function drawTable() {&nbsp; &nbsp; console.log('draw');&nbsp; &nbsp; &nbsp; &nbsp; // get the reference for the body&nbsp; &nbsp; &nbsp; &nbsp; var first = document.getElementById('first');&nbsp; &nbsp; &nbsp; &nbsp; // creates a <table> element&nbsp; &nbsp; &nbsp; &nbsp; var tbl = document.createElement("table");&nbsp; &nbsp; &nbsp; &nbsp; // creating rows&nbsp; &nbsp; &nbsp; &nbsp; for (var r = 0; r < totalRows; r++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var row = document.createElement("tr");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// create cells in row&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;m=0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (var c = 0; c < cellsInRow; c++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cell = document.createElement("td");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cellText = document.createTextNode(units[n][key[m]]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cell.appendChild(cellText);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.appendChild(cell);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m=m+1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n=n+1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(row);&nbsp; &nbsp; tbl.appendChild(row); // add the row to the end of the table body&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;first.appendChild(tbl); // appends <table> into <first>}&nbsp; &nbsp; // your code herewindow.onload=drawTable();&nbsp;<div id='first'></div>

慕妹3146593

您可以通过利用DOM API和Array.prototype.reduce方法轻松实现这一点 - 例如:const units = [{    'code': 'COMP2110',    'title': 'Web Technology',    'offering': 'S1'  },  {    'code': 'COMP2010',    'title': 'Algorithms and Data Structures',    'offering': 'S1'  },  {    'code': 'COMP2150',    'title': 'Game Design',    'offering': 'S1'  },  {    'code': 'COMP2320',    'title': 'Offensive Security',    'offering': 'S1'  },  {    'code': 'COMP2200',    'title': 'Data Science',    'offering': 'S2'  },  {    'code': 'COMP2250',    'title': 'Data Communications',    'offering': 'S2'  },  {    'code': 'COMP2300',    'title': 'Applied Cryptography',    'offering': 'S2'  },  {    'code': 'COMP2000',    'title': 'Object-Oriented Programming Practices',    'offering': 'S2'  },  {    'code': 'COMP2050',    'title': 'Software Engineering',    'offering': 'S2'  },  {    'code': 'COMP2100',    'title': 'Systems Programming',    'offering': 'S2'  }];const createEmptyTable = () => {  const tableEl = document.createElement('table');  tableEl.appendChild(document.createElement('thead'));  tableEl.appendChild(document.createElement('tbody'));  return tableEl;};const createTableHeadersRow = data => {  const fields = Object.keys(data);  return fields.reduce((trEl, fieldName) => {    const tdEl = document.createElement('th');    tdEl.appendChild(document.createTextNode(fieldName));    trEl.appendChild(tdEl);    return trEl;  }, document.createElement('tr'));};const createTableBodyRow = data => {  const values = Object.values(data);  return values.reduce((trEl, value) => {    const tdEl = document.createElement('td');    tdEl.appendChild(document.createTextNode(value));    trEl.appendChild(tdEl);    return trEl;  }, document.createElement('tr'));};const createUnitTable = unitsArray => {  return unitsArray.reduce((tableEl, unit, idx) => {    const tableNeedsHeaderRow = idx === 0;    if (tableNeedsHeaderRow) {      tableEl.querySelector('thead').appendChild(createTableHeadersRow(unit));    }    tableEl.querySelector('tbody').appendChild(createTableBodyRow(unit));    return tableEl;  }, createEmptyTable());};document.querySelector('div').appendChild(createUnitTable(units));td {  padding: .5rem;  border: 1px solid black;}th {  text-transform: capitalize}<div></div>

至尊宝的传说

对象数组示例let cars = [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "color": "purple",&nbsp; &nbsp; &nbsp; &nbsp; "type": "minivan",&nbsp; &nbsp; &nbsp; &nbsp; "registration": new Date('2017-01-03'),&nbsp; &nbsp; &nbsp; &nbsp; "capacity": 7&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "color": "red",&nbsp; &nbsp; &nbsp; &nbsp; "type": "station wagon",&nbsp; &nbsp; &nbsp; &nbsp; "registration": new Date('2018-03-03'),&nbsp; &nbsp; &nbsp; &nbsp; "capacity": 5&nbsp; &nbsp; &nbsp; }]功能 :function ArrayToHtmlTable(htmlelement,ArrayObject) {&nbsp; TableHeader = Object.keys(ArrayObject[0])&nbsp; &nbsp; .map((x) => "<th>" + x + "</th>")&nbsp; &nbsp; .join("");&nbsp; TableBody = ArrayObject.map(&nbsp; &nbsp; (x) =>&nbsp; &nbsp; &nbsp; "<tr>" +&nbsp; &nbsp; &nbsp; Object.values(x)&nbsp; &nbsp; &nbsp; &nbsp; .map((x) => "<td>" + x + "</td>")&nbsp; &nbsp; &nbsp; &nbsp; .join() +&nbsp; &nbsp; &nbsp; "<tr>"&nbsp; ).join("");&nbsp; document.getElementById(&nbsp; &nbsp; htmlelement&nbsp; ).innerHTML += `<table> ${TableHeader} ${TableBody}</table>`;}函数调用:ArrayToHtmlTable("testTable",cars)&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5