Creating a table in Javascript using an array of objects

I need a larger version of this data structure.

[{
"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 have been struggling for hours to convert this array into a table format.

My objective is to display the last zones (in this case zone2 and zone3) from the voting_section in the first column of the table (e.g. the first column will list: Delaware and Los Angeles).

I want to include all other properties (votes, invalid votes, valid votes) in the table header.

The table cells should be filled with corresponding values:

This is what I am aiming for:

https://i.sstatic.net/Ncjs9.jpg

This is the code I have so far, but I believe I may not be on the right track:

 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 refers to a node in the DOM.

Answer №1

Upon analyzing your inquiry, it appears that you are interested in extracting a single zone from the voting_section data, specifically the one with the highest numerical value associated with it.

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>

Answer №2

If you want to streamline the process of building a table, consider creating a main function that handles the overall table creation and then calling a separate function for building each row as you iterate over the data. I've provided an example in my post below.

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){
  /* A function that constructs a single 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>`;
  }
  
  /* Combines all rows from the array of row data into one string */
  var rows = data.reduce(function(rows, row){
    return rows+buildRow(row);
  }, '');
  
  /* Builds the complete table with the concatenated rows */
  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>

Answer №3

To generate a table using the javascript DOM objects, you can follow these steps:

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")
    //Ensures the table is empty if called multiple times
while(table.rows[0] !== undefined) {
    table.deleteRow(0)
}
    //Creates empty cell in top left corner
row = table.insertRow(0)
row.insertCell(0)
pos = 0

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

    //Inserts row labels based on data
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
}

    //Fills in the values in the table
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]
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on implementing a bootstrap loading spinner during the process of retrieving data from an external api

Is there a way to use the bootstrap load spinner to mask the delayed information retrieval from a url and enhance the website's interactivity? ...

List of duplicated BLE devices detected in network scanning

Greetings! I am currently working on an Ionic project named BLE Scanner. After facing some challenges, I finally managed to connect to the devices. Below is the code snippet that I discovered online: home.ts (please ignore the DetailPage) import { Compon ...

Ways to extract the ID by iterating through buttons

I encountered a message in my browser while looping through buttons with onclick function(). Are there any alternative solutions? Error handling response: TypeError: self.processResponse is not a function at chrome-extension://cmkdbmfndkfgebldhnkbfhlneefd ...

Angular-datatables has a scroller function that allows for easy navigation within the content of

I've been scouring the web for hours, but I can't seem to find a solution. Can someone please assist me in resolving this issue? Issue: I integrated angular-datatables within an md-tab using Angular material. Everything was running smoothly unti ...

Component does not detect change when the same number is sent as input

Let me paint you a picture: I have this nifty component, set up with the OnPush strategy, that showcases a PDF document, sliding through pages one by one, and granting users the ability to smoothly glide through pages and jump to specific ones. It even of ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

watchify with gulp requires two saves to update modifications

For a while now, I've been experimenting with watchify and encountering a saving issue. It appears that every time I make a change, I have to save twice for the modifications to reflect in the output. If I add new code to any JavaScript file, the ch ...

When I try to use Node.js and Express, I encounter an issue where I receive the

I recently developed a basic application. Everything was running smoothly until I decided to organize the code using an MVC template. However, now when you visit localhost:3000/add-service, you are greeted with a "Cannot Get /add-service" error message. W ...

Dealing with JSON data retrieved from a Django QuerySet using AJAX

I am utilizing a Django QuerySet as a JSON response within a Django view. def loadSelectedTemplate(request): if request.is_ajax and request.method == "GET": templateID = request.GET.get("templateID", None) ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Guide on making a button display an image, then switch back to the initial image when clicked again

Currently, I have this neat feature on my website where there's a button that toggles the image/background color - kind of like a dark mode switch. The background change is working fine, but I'm encountering some challenges with organizing the im ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

Adding double quotes, where they haven't been added yet

I am trying to work with the following string (Very strong=="Very strong"?100:(Very strong=="Above Average"?75:(Very strong=="Average"?50:(Very strong=="Below Average"?25:(Very strong=="Cannot determine"?0:(Very strong=="Poor"?0:0)))))) My desired outpu ...

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...

terminate the express middleware and return a custom HTTP status code

Is it possible to use custom middleware to return a 404 or 401 error to the user and prevent other handlers from running? I tried implementing the following code: function SomeMiddleware(req, res, next) { if(user.notRealOrSomething) { throw new Htt ...

Animate an image to the right when clicked, then return it to the left with a second click

Seeking help with animating a set of images to move individually 300px right on first click, and then 300px left when clicked again. I'm currently facing an issue where my code is not working. It could be due to A) syntax errors or B) the images not ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

How can I transfer request headers from Express to index.js in React?

Is there a way to store user-related information received in the request headers of the Express server as a runtime variable accessible in index.js? I need to apply conditional routing based on these parameters. Alternatively, is there a way to pass these ...

Understanding the implementation of options within dataTables that have been initialized with an aaData JavaScript array

When initializing my datatable, I used an aaData object and specific options like so: $('#dataTable').dataTable(dataTableObj, { "bPaginate": false, "bLengthChange": false, "bFilter": true, "bSort": false, "bInfo": false, ...