What is the best approach for creating a dynamic table in this situation?

I am struggling with creating a table from a variable that contains an array of arrays, which is parsed code from an excel file.

I attempted to upload the file and build the table using the following approaches:

tabela.forEach((elem, index) => {
  console.log(elem[0], index[1])
  const row = tableBody.insertRow(index)
  const employeeCell = row.insertCell(0)
  let content = document.createTextNode(elem[0])
  employeeCell.appendChild(content)
})

and also tried this method:

for (let i = 1; i < tabela.length; i++) {
  const row = tableBody.insertRow(tabela[1])
  const employeeCell = row.insertCell(0)
  let content = document.createTextNode(tabela[0])
  employeeCell.appendChild(content)
}

Unfortunately, both approaches have yielded unexpected results.

I really want to comprehend what I am doing wrong but seem to be facing difficulties.

The variable tabela consists of 13 elements, each being an array with 7 elements.

Can anyone offer guidance on how to correctly build a table using the parsed code stored in the "tabela" variable?

Answer №1

To properly display each element in the row, you will need to iterate through them and add a cell for each element.

tabela.forEach(elem => {
  const row = tableBody.insertRow();
  elem.forEach(item => {
    const cell = row.insertCell();
    cell.innerText = item;
  });
})

Answer №2

Learn how to achieve your goal using the power of jQuery with this demonstration.

const arrayTable = [
    [10,20,30,40,50],
    [100,200,300,400,500],
    [1,4,7,10,13]
];
let $tableBody = $('#table-data tbody');
$tableBody.html(
    arrayTable.map(row => $('<tr/>').html(
        row.map(cell => $('<td/>').html( cell ))
    ))
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table-data"><tbody></tbody></table>

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

Issue with AngularJS compatibility on first generation iPad

Having trouble with my first generation iPad while trying to implement a basic ngRoute and ngAnimate setup. It's working fine on desktop and iPhone 6, but not on the iPad. The error message I'm encountering is: Error[$injector:modulerr]http://e ...

Enhance the current MultiSelect object by incorporating JQuery MultiSelect

Is there a way to detect changes on a JQuery MultiSelect in order to trigger an update elsewhere? The typical javascript onchange method does not seem to work because the select itself does not change. However, I came across a method called "beforeclose" t ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

What are the various undisclosed schema types in A-Frame?

I've been exploring different examples of property types in the official documentation and various Github repositories (though now I can't remember which ones). The latter introduced me to unique properties like "min" and "max" for numbers, as we ...

Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe. Please review the codesandbox json file first. The objective is to capture the total calories and nutritive c ...

How come the useState function remains undefined, even when initialized with a default value?

I attempted to set an empty array as the default value for a state using the useState hook in React. However, when I try to check the type of testing with console.log(Array.isArray(testing)); or simply log testing, it always displays undefined regardless o ...

A versatile function that displays a loading icon on top of a specified div

Is it possible to pass an identifier for a particular div element to a function, where the function will display a loading image that covers the entire div, and then pass the same identifier to another function to hide the loading image? I am looking to cr ...

Firebase ref.on('value') will repeatedly trigger, even if no changes have occurred

My current setup involves using an event listener to monitor changes in my real-time database. const [chats, setChats] = useState({}); const ref = db.ref(`users/${sender}/chat/`); ref.on('value', (snapshot) => { const data = snapshot ...

Unable to retrieve data in Node Express after querying completion

I created a basic custom module that is intended to return database records from its methods. After executing a query, I can retrieve all the records but when attempting to assign them to a variable, it shows as null. I'm unsure of what's causin ...

How to append a JSON object to an existing .json file

UPDATE: Despite successfully executing the PHP code, my JSON file remains unchanged. I must apologize in advance for covering old ground, but I have spent countless hours exploring different solutions with no success. Perhaps sharing my challenge could as ...

String ES6 syntax immediately after function

return pool.query`select * from mytable where id = ${value}` How can the code snippet above be rewritten in full JavaScript? I attempted to use: return pool.query(`select * from mytable where id = $(value)`) but it seems like there is a difference. Th ...

Having an issue with fastify-multer where request.files is coming back as undefined during testing with Postman

In the process of developing an API that consumes multipart/form-data using fastify, I've integrated the fastify-multer plugin to handle file uploads for passing them to another third-party API. Currently, I'm testing with Postman, but encountere ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

The drop-down menu remains visible even after clicking outside of it

I've written a script that works when clicked, but it doesn't hide when clicked outside of it. $(document).ready(function() { //Translate(); //caling Language Translater function $("#translate_image").attr('href', base_url) ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated. app.component.ts: ngOnInit(): void ...

The phenomenon of jQuery AJAX converting the escape character from %20 to + has been observed

I am encountering an issue with my jQuery AJAX function which is supposed to save an image path to the database. Below is an example parameter: var data = {}; data['url'] = "Path%20to%20URL"; Normally, if there is a space or %20, it sh ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

Is there a way I can maintain the active state after clicking on a link?

Is there a way to maintain an active element state when navigating to another page after clicking a link? I am wondering if it is possible to use JavaScript to remove the active state from one link and apply it to the next one. I am facing some challenges ...

Error: Element type is invalid: a string was anticipated, but not found

I recently experimented with the example provided in React's documentation at this link and it functioned perfectly. My objective now is to create a button using material-ui. Can you identify what is causing the issue in this code? import * as R ...