Creating tables from arrays in JavaScript by using an array value as a variable name for a function argument can be achieved through the following steps

I am looking to generate tables with data derived from arrays. Each table will have its own array of data and I also have an array that contains the names of the table data arrays along with some additional values.

It seems like the issue lies in table(x[1],sub) because x[1] is not being treated as a variable name, but rather its value is acting as a string.

In PHP, you could use something like $$x[1], but how can this be achieved in JavaScript?

var xxx = [[ 'Adam'    , 'table1' ],
           [ 'Ben'     , 'table2' ],
           [ 'Charlie' , 'table3' ]];

// arrays for table data

var table1 = [[ 'a' , '1' ],
              [ 'b' , '2' ],
              [ 'c' , '3' ],
              [ 'd' , '4' ],
              [ 'e' , '5' ]];
              
var table2 = [[ 'a' , '1' ],
              [ 'b' , '2' ],
              [ 'c' , '3' ],
              [ 'd' , '4' ],
              [ 'e' , '5' ]];
              
var table3 = [[ 'a' , '1' ],
              [ 'b' , '2' ],
              [ 'c' , '3' ],
              [ 'd' , '4' ]],

// function to create table

function table(tableData,sub) {
  var table     = document.createElement('table');
  var tableBody = document.createElement('tbody');

  tableData.forEach(function(rowData) {
    var row = document.createElement('tr');

    rowData.forEach(function(cellData) {
      var cell = document.createElement('td');
      cell.appendChild(document.createTextNode(cellData));
      row.appendChild(cell);
    });

    tableBody.appendChild(row);
  });

  table.appendChild(tableBody);
  
  sub ? sub.appendChild(table) : document.body.appendChild(table);

}

// apply everything to HTML

xxx.forEach( x => {

  var con = document.querySelector('#content');
  var sub = document.createElement('div');
 
  con.appendChild(sub);
  
  var h = document.createElement('h3');
  h.innerHTML = x[0];
  
  sub.appendChild(h3);
  table(x[1],sub);      // x[1] presents an issue

});
<div id="myID">
  <h2>Headline</h2>
  <div id="content">
  
  </div>
</div>

Answer №1

If you need to access specific tables by their names, one approach is to create a reference object containing the table names.

reference = { table1, table2, table3 }

function table(tableData, sub) {
    var table = document.createElement('table'),
        tableBody = document.createElement('tbody');

    tableData.forEach(function(rowData) {
        var row = document.createElement('tr');
        rowData.forEach(function(cellData) {
            var cell = document.createElement('td');
            cell.appendChild(document.createTextNode(cellData));
            row.appendChild(cell);
        });
        tableBody.appendChild(row);
    });
    table.appendChild(tableBody);
    (sub || document.body).appendChild(table);
}

var xxx = [['Adam', 'table1'], ['Ben', 'table2'], ['Charlie', 'table3']],
    table1 = [['a', '1'], ['b', '2'], ['c', '3'], ['d', '4'], ['e', '5']],
    table2 = [['a', '1'], ['b', '2'], ['c', '3'], ['d', '4'], ['e', '5']],
    table3 = [['a', '1'], ['b', '2'], ['c', '3'], ['d', '4']],
    reference = { table1, table2, table3 }; // refernce 

xxx.forEach(x => {
    var con = document.querySelector('#content'),
        sub = document.createElement('div'),
        h = document.createElement('h3');

    con.appendChild(sub);
    h.innerHTML = x[0];
    sub.appendChild(h);          // use h insead of h3
    table(reference[x[1]], sub); // reference
});
<div id="myID">
  <h2>Headline</h2>
  <div id="content"></div>
</div>

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

Can I maintain the separation of two arrays in Angular and still utilize them in an ng-repeat?

Before we proceed, let's reference this question: Angularjs map array to another array Presently, I am managing two distinct scopes: $scope.products = [ {id: 001, name: "prod 1", ...}, {id: 002, name: "prod 2", ...}, {id: 003, name: "prod 3", ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Enhance the v-autocomplete dropdown with a personalized touch by adding a custom

Currently utilizing the v-autocomplete component from Vuetify, and I am interested in incorporating a custom element into its dropdown menu. You can see the specific part I want to add highlighted with a red arrow in this screenshot: This is the current s ...

Generate a random post on a Blogger page upon loading instead of clicking on it

I recently implemented a random post button on my website at . I am now looking to have a random post load automatically when the page loads instead of requiring users to click the button. Can anyone provide guidance on how I can achieve this? Below is t ...

Filtering Gridviews with Javascript or jQuery

My current project involves using an ASP.NET GridView with multiple ListBoxes representing Departments, Categories, Faculties, and more. The data in these ListBoxes and the GridView is dynamically loaded from a MSSQL database in the codebehind. I am in ne ...

definition of a function with another function

I'm curious about whether it's considered a good practice in JavaScript to define a function within another function. Take a look at this code snippet: module.exports = function() { function foo() { // do something } ... foo() .. ...

How can one easily implement a countdown timer in an Ionic 3 app?

Easily create an Ionic3 timer set to 2 minutes that displays countdown like 1:59, 1:58, and finally reaches 00:00. Once the timer hits 00:00, a block of HTML content will be shown. ...

Allocate memory for a two-dimensional character array using malloc

I'm attempting to dynamically allocate memory for a char array with rows and columns, each cell containing one letter. Something akin to an int x[i][j] setup where there are i*rows and j*columns displayed. Essentially, I aim to represent this pattern: ...

When attempting to start the server in Node.js, an error is thrown stating that the issue needs to be resolved with a middleware function

I am experiencing an issue when attempting to start the server after creating a route and using it in the app.js file. I need assistance in resolving this error as I have been stuck on it for hours. I have made several edits but none seem to work. Here is ...

`amqplib - What is the current number of active consumers on the queue?`

Seeking insight on using the amqplib module for Node JS and RabbitMQ: 1) Is there a method to determine the number of subscribers on a queue? 2) What is the process for ensuring that each queue has only one consumer key? Appreciate any guidance! ...

Error on page refresh: Unable to access properties of null while attempting to read 'addEventListener'

Having a couple of HTML pages where I load code snippets using jQuery's .load method. Here is an example from my index.html: $('#rotating-content').load(`./snippets/shared/rotating-content.html`); The "rotating-content.html" contains two Bo ...

Function in AngularJS to increment counts based on matching names

Check out my angular application on this Plunker link The text area in my app contains data in the format of (key, count). My goal is to sum up these values using the calc() function. When the user clicks the button, I want the total summation to be disp ...

What is the method to extract a data array from an hdf5 file in Python 3.6 when the data type is "<u4"?

I am looking to extract a dataset in the format {N, 16, 512, 128} as a 4D numpy array from an hdf5 file. N represents the number of 3D arrays with {16, 512, 128} dimensions. Here is what I have tried: import os import sys import h5py as h5 import numpy as ...

Even though setState is supposed to update the state and trigger a render, it's not showing up in the view for some

My React app consists of a simple word/definition feature. There is an edit box that appears for users to change the definition when they click on "edit". Even though I call getGlossary() to update the new definition in the state, I can see the changes in ...

How to trigger a JavaScript refresh during debugging in Visual Studio 2012

Currently, I am grappling with debugging scripts in my ASP.NET project using VS2012. Whenever I initiate the project, errors start to appear from a third-party library. The issue I am facing is that even after making changes to the scripts, they are not r ...

Transferring PHP Arrays to JavaScript with JQuery

I am facing an issue with redrawing markers (on Google Maps) from a database using jQuery form. Here is the code snippet: Index.html: var map; var data; function updateLocations(){ var post= $.post('php/getLoc.php',{table: "Auto"), functio ...

What is the best way to retrieve the innerHTML content from several Quill instances that share the same class identifier?

I have successfully implemented multiple Quill text editor instances on a single page. However, I am now facing a challenge in retrieving the innerHTML of each instance. When creating a single instance and assigning its innerHTML to a hidden input field, I ...

Transforming an Array of Dictionaries into a Single Object

If there is an array of dictionaries stored in my NSUserDefaults: ["name":"John", "birthplace":"New York"] ["name":"Eric", "birthplace":"London"] ["name":"Sven", "birthplace":"Stockholm"] ["name":"Pierre", "birthplace":"Paris"] What is the most efficient ...

What is the best way to smoothly transition from one video to another with a simple click?

I am looking to enhance my website by implementing a feature where a video will play when a button is clicked, and then another video will smoothly fade in while fading out the current video upon clicking a different button. This transition should dynamica ...

What is the best way to combine every item in one array with every item in another array using Ruby?

Let's say we have the following array: [0, 1, 4], [2, 3] Is there a way to combine them to achieve the following result? [0,2], [0,3], [1,2], [1,3], [4,2], [4,3] One attempt was: [0, 1, 4].merge [2, 3] However, the output was: [[0, 2], [1, 3], ...