繁体   English   中英

如何从 Object 动态创建具有 Javascript 和/或 JQuery 的表?

[英]How to create a table with Javascript and/or JQuery dynamicaly from an Object?

我正在尝试使用 javascript 创建一个动态表,如果“M”具有相同的值,则应该对“A”中的值求和。 此外,表 header 应根据“代码”中的值创建。 很抱歉我不能更好地描述它,但我希望我的例子能说明我的意思。

 var arr = [{ "M": "52800", "Code": "093", "A": 1 }, { "M": "52800", "Code": "050", "A": 2 }, { "M": "56301", "Code": "093", "A": 3 }, { "M": "57401", "Code": "060", "A": 1 }, { "M": "57401", "Code": "090", "A": 5 }, { "M": "57401", "Code": "093", "A": 3 }, { "M": "57401", "Code": "080", "A": 5 }]; console.log(arr);

结果表应如下所示:

093 050 060 090 080
52800 1 2
56301 3
57401 3 1 5 5

你可以这样做(评论中的解释):

 var arr = [{ "M": "52800", "Code": "093", "A": 1 }, { "M": "52800", "Code": "050", "A": 2 }, { "M": "56301", "Code": "093", "A": 3 }, { "M": "57401", "Code": "060", "A": 1 }, { "M": "57401", "Code": "090", "A": 5 }, { "M": "57401", "Code": "093", "A": 3 }, { "M": "57401", "Code": "080", "A": 5 }]; //distinct M values for rows const rows = [...new Set(arr.map(item => item.M))]; //distinct Code values for columns const cols = [...new Set(arr.map(item => item.Code))]; let table = document.createElement("table"); let tableHead = document.createElement("thead"); let head = "<tr><th>M</th>"; //populate header row with values in cols array cols.forEach(col => head += "<th>" + col + "</th>"); head += "</tr>"; tableHead.innerHTML = head; let tableBody = document.createElement("tbody"); //body will contain table rows let body = ""; rows.forEach((row, index) => { //open table row and add value from rows array body += "<tr><td>" + row + "</td>"; //populate row with corresponding values or empty cell cols.forEach(col => { //try to find if there is a "A" value associated with current col and row let value = arr.find(el => el.M === row && el.Code === col); let cell = value? value.A: ""; body += "<td>" + cell + "</td>"; }); body += "</tr>"; }); tableBody.innerHTML = body; table.appendChild(tableHead); table.appendChild(tableBody); document.body.appendChild(table);
 table, th, td { border: solid 1px black; }

暂无
暂无

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

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