来自对象数组的Javascript表

时间:2017-05-30 23:01:53

标签: javascript arrays tabular

我有类似的东西,但更大。

[{
"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"}
}]

我正在努力将这个数组转换成表格。

我的目标是在表格的第一列放置vote_section中的最后一个区域(在我们的例子中为zone2和zone3)(例如,第一列将有两行:Delaware和Los Angeles。

在表格的标题中,我想放置所有其他属性(votes,invalid_votes,valid_votes)。

将使用以下值完成交集:

所以它必须是这样的:

Table

到目前为止,我有我的代码,但我不认为我的方向很好:

 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是DOM中的一个节点。

3 个答案:

答案 0 :(得分:1)

我已经解释了你的问题,好像你想从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>

答案 1 :(得分:0)

您可以创建一个主要函数来构建表,从中可以调用行构建函数(在迭代数据行时)。我在这里的帖子中添加了一个例子。

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>

答案 2 :(得分:0)

您可以使用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]
        }
    }
}