简体   繁体   English

对象数组中的Javascript表

[英]Javascript table from array of objects

I have something like this, but bigger. 我有这样的东西,但更大。

[{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}]

I am trying for hours to transform this array into a table. 我试图用几个小时将这个数组转换成一个表。

My goal is to put in the first column of the table the last zones (in our case zone2 and zone3) in voting_section (for example, the first column will have 2 lines: Delaware and Los Angeles. 我的目标是在表的第一列中将voting_section中的最后一个区域(在我们的示例中为zone2和zone3)放入(例如,第一列将有两行:特拉华州和洛杉矶)。

In the header of the table I want to put all the other properties(votes, invalid_votes, valid_votes). 在表格的标题中,我要放置所有其他属性(投票,invalid_votes,valid_votes)。

The intersection will be completed with the values: 相交将使用以下值完成:

So it has to be something like this: 所以它必须是这样的:

表

Here I have my code so far, but I don't think I'm going in a good direction: 到目前为止,这里有我的代码,但是我认为我的方向并不正确:

 function createTableKeyValue2(arrObjects, parentDiv) {
                var elTable = document.createElement("table");
                elTable.className = "table table-striped table-bordered";
                var elTableBody = document.createElement("tbody");
                for (var i = 0; i < arrObjects.length; i++) {
                    var elTableRow = document.createElement("tr");
                    var elTableDataKey = document.createElement("td");
                    elTableDataKey.innerHTML = arrObjects[i];
                    var elTableDataValue = document.createElement("td");
                    elTableDataValue.innerHTML = arrObjects[i];
                    //elTableDataValue.id = arrObjects[i].key.split(' ').join('_');
                    elTableRow.appendChild(elTableDataKey);
                    elTableRow.appendChild(elTableDataValue);
                    elTableBody.appendChild(elTableRow);
                }
                elTable.appendChild(elTableBody);
                parentDiv.append(elTable);
            }

            var votingSection = function(zone) {

                var voting_section = [];
                var level = zone[0].voting_section.level;
                for (var i = 0; i < zone.length; i++) {
                    voting_section.push(zone[i].voting_section['zone' + level]);
                }
                return voting_section;
            };

createTableKeyValue(votingSection(zone2), resultsTableDiv);

resultTableDiv is a node in the DOM. resultTableDiv是DOM中的一个节点。

I've interpreted your question as though you want to extract 1 zone from voting_section, that zone should have the highest number appended to it. 我已经解释了您的问题,好像您要从voting_section中提取1个区域一样,该区域应附加最高编号。

 var data = [{ "votes": 200, "invalid_votes": 140, "valid_votes": 60, "voting_section": { "level": 1, "zone1": "US", "zone2": "Delaware" } }, { "votes": 300, "invalid_votes": 40, "valid_votes": 260, "voting_section": { "level": 1, "zone1": "US", "zone2": "California", "zone3": "Los Angeles" } } ], html = ""; function getLastZone(voting_section) { var highestZone = { zoneNumber: null, zoneText: null }; for (var zone in voting_section) { var checkZone = /zone(\\d)/g.exec(zone); if (checkZone) { if (parseInt(checkZone[1]) > highestZone.zoneNumber) { highestZone = { zoneNumber: [checkZone[1]], zoneText: voting_section[zone] }; } } } return highestZone.zoneText; } data.forEach(function(e, i) { html += "<tr>" + "<td>" + getLastZone(e.voting_section) + "</td>" + "<td>" + e.votes + "</td>" + "<td>" + e.valid_votes + "</td>" + "<td>" + e.invalid_votes + "</td>" + "</tr>"; }) document.getElementById("putHere").innerHTML = html; 
 table { border-collapse: collapse; border-left: 1px solid #bbbbbb; border-top: 1px solid #bbbbbb; } th, td { border-right: 1px solid #bbbbbb; border-bottom: 1px solid #bbbbbb; } 
 <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <table> <thead> <th>Zone</th> <th>Votes</th> <th>Valid Votes</th> <th>Invalid Votes</th> </thead> <tbody id="putHere"></tbody> </table> </body> </html> 

You could create one main function to build the table, from which you could call a row-building function (while iterating over the data rows). 您可以创建一个主函数来构建表,从中可以调用行构建函数(在数据行上进行迭代)。 I've added an example to my post here. 我在此处添加了一个示例。

 var data = [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"} }]; var buildTable = function(data, container){ /* Builds one data row into a <tr> element string */ var buildRow = function(rowData){ return `<tr><td>${rowData.voting_section.zone2}</td><td>${rowData.votes}</td><td>${rowData.valid_votes}</td><td>${rowData.invalid_votes}</td></tr>`; } /* Reduces the array of row data into one string */ var rows = data.reduce(function(rows, row){ return rows+buildRow(row); }, ''); /* Creates the full table and includes the rows string */ container.innerHTML = `<table><thead><tr><td></td><td>Votes</td><td>Valid Votes</td><td>Invalid Votes</td></tr></thead><tbody>${rows}</tbody>`; } var resultsTableDiv = document.getElementById('results') buildTable(data, resultsTableDiv); 
 <div id="results"></div> 

You can create a table from it using the javascript DOM objects, 您可以使用javascript DOM对象从中创建表,

myArray = [{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}]

table = document.getElementById("myTable")
    //In case is is called multiple times this forces the table to be empty
while(table.rows[0] !== undefined) {
    table.deleteRow(0)
}
    //Creates the empty cell in the top left
row = table.insertRow(0)
row.insertCell(0)
pos = 0

    //Creates the column labels
for(var name in myArray[0]) {
    if (name !== "voting_section") {
        pos += 1
        cell = row.insertCell(pos)
        cell.innerHTML = name
    }
}

    //creates the row labels, by changing how the last item is selected or what it contains you can produce a different label
for (var i = 0; i < myArray.length; i++) {
    row = table.insertRow(i+1)
    lastItem = myArray[i].voting_section[Object.keys(myArray[i].voting_section)[Object.keys(myArray[i].voting_section).length - 1]]
    row.insertCell(0).innerHTML = lastItem
}

    //creates the values
pos = 0
for(var name in myArray[0]) {

    if (name !== "voting_section"){
        pos += 1
        for (var i = 0; i < myArray.length; i++) {
            row = table.rows[i+1]
            cell = row.insertCell(pos)
            cell.innerHTML = myArray[i][name]
        }
    }
}

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

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