Tips for generating a dynamic JavaScript object that contains a function as its value

I am in search of a dynamic method to generate Quasar Table column definitions. While the existing method shown below does work, I believe that replacing the lengthy switch statement with a for loop would be a more efficient solution.

How can I implement a for loop to achieve the same outcome as the code provided:

const createTableColumns = (numberOfColumns: number) => {
  const tableCols: QTableProps["columns"] = [];
  const numberOfColumnsStr = numberOfColumns.toString();

  switch (numberOfColumnsStr) {
    // Cases for each specific column
  }

  tableCols.sort((a, b) => parseInt(a.name) - parseInt(b.name));
  return tableCols;
};

I have attempted the following alternative approach using a for loop:

const tableCols2: QTableProps["columns"] = [];

for (let colIndex = 0; colIndex < numberOfColumns; colIndex++) {
  const rowKeyArray = [...]; // Array containing keys for each column
  const colNumber: number = colIndex + 1;
  const rowKey: string = rowKeyArray[colIndex];
  
  const myObj = {
    name: colNumber.toString(),
    align: "center",
    label: colNumber.toString(),
    field: (row) => row[rowKey].value,
    format: (val, row) => (row[rowKey].isSlected ? `** ${val} **` : `${val}`),
    sortable: false,
  };

  tableCols2.push(myObj);
}

Answer №1

One possible approach could involve using objects instead:

let keyMap = {
  '1': 'one',
  '2': 'two',
  // ...
}
let colIndex: keyof typeof keyMap;
const tableCols2: QTableProps["columns"] = [];

for (colIndex in keyMap) {
  const rowKey: string = keyMap[colIndex];
  const myObj = {
    name: colIndex,
    align: "center",
    label: colIndex,
    field: (row) => row[rowKey].value,
    format: (val, row) => (row[rowKey].isSelected ? `** ${val} **` : `${val}`),
    sortable: false,
  };

  tableCols2.push(myObj);
}

Answer №2

To make things simpler, take a look at this potential solution using vanilla JS:

const createTableColumns = (numberOfColumn) => {
  const englishNames = "zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen".split(',');
  if( numberOfColumn < 1 || numberOfColumn >= englishNames.length) throw("invalid number of columns: " + numberOfColumn);
  
  const tableCols = [];
  for(let col = numberOfColumn; col >= 2; col--) {
    const colAsString = col.toString();
    const colAsEnglish = englishNames[col];
    const obj = {
        name: colAsString,
        align: "center",
        label: colAsString,
        field: (row) => row[colAsEnglish].value,
        format: (val, row) => (row[colAsEnglish].isSlected ? `** ${val} **` : `${val}`),
        sortable: false,
      };
    tableCols.push(obj);
  }
  tableCols.push({
    name: "1",
    align: "center",
    label: "1",
    field: (row) => row.name,
    format: (val, row) => `${val}`,
    sortable: false,
  });

  tableCols.sort((a, b) => parseInt(a.name) - parseInt(b.name));
  return tableCols;
}


// test ----------------------------------------------

const tableCols = createTableColumns(3);
const row = {
   name: "test row name",
   "one": {value: "not used", isSlected: false},
   "two": {value: "row.two column content", isSlected: true},
   "three": {value: "row.three column content", isSlected: false}
};

for( let index = 0; index < tableCols.length; ++index) {
  let colObj = tableCols.find( obj=>obj.name === (index+1).toString());
  const value = colObj.field(row);
  const string = colObj.format(value, row);
  console.log( string)
};

Note:

  • The provided code showcases a different approach than previous versions as the methods "field" and "format" for the column object named "1" have been adjusted from those in other columns. This adjustment was made by pushing the column object "1" outside the loop. The updated code appears to produce the expected results: executing the test code with the revised version of createTableColumns yielded consistent log output.

  • In the code snippet above, the "for" loop utilizes "let" and "const" declarations to ensure column values are stored appropriately for each iteration. Consequently, the variables colAsString and colAsEnglish utilized in the function methods of obj (field and format) pertain specifically to the iteration in which they were defined.

Now, a few considerations for you:

  1. Assigning English number names to the row column properties may complicate maintenance. Opting for calculated column property names like "C1," "C2," ... "C15" based on numerical order could offer a more straightforward alternative.

  2. The title of the question raises some ambiguity: an object whose value is a function technically qualifies as a function.

  3. The test code exhibits a cautious approach by finding column data based on name strings. However, it does not validate the structural integrity of the row object. Keep in mind that this is solely test code!

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

Trouble with Next.js App Router OG Image not appearing after deployment

I am facing an issue with my Nextjs project that uses the app router. Inside the app directory, there is a file named opengraph-image.png. I have set this file to be the OG Image for the landing page, but after deploying and checking, the OG image does not ...

ng-repeat isn't displaying the data

I have always been comfortable using the ng-repeat in Angular, but this time I seem to be facing a problem. I am trying to populate my DOM with data from a JSON file, but for some reason, the fields are not displaying as expected. Is there something wrong ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

encountering an error of unsupported grant type while attempting to authenticate a user

I've seen a lot of discussions on this topic, but none have addressed my specific issue. Currently, I am working on an angular 5 application and trying to retrieve an authentication token by sending a post request to a server. Testing the connection ...

I attempted to utilize body-parser, but it appears that it is not functioning properly

I am having trouble with body parser and express as it is not functioning properly. When I print req.body in the console, it returns an empty object. var express = require('express'); var app = express(); var bodyParser = require('body-pars ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

Function in Typescript used for checking types and catching compilation errors from external sources

Fact: I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable and returns 'undefined' !== typeof variable). It's quite simple. export function IsDefined(variab ...

The fetch API does not retain PHP session variables when fetching data

After setting session variables in one php file, I am attempting to access those values in another php file. session_start(); $_SESSION['user'] = $row['user']; $_SESSION['role'] = $row['role']; However, when ...

Is Nuxt's FingerprintJS Module the Ultimate Server and Client Solution?

I am currently using fingerprintJS in my NuxtJS+Firebase project VuexStore. When I call the function on the client side, I can retrieve the Visitor ID. However, I am encountering issues when trying to use it on the server side, such as in nuxtServerInit. ...

How does BodyParser from Express handle a request that results in a Bad Request with a Status

I am currently working with Node and Express. Here is the function I am using to fetch JSON data from the server: $.ajax({ url: url, contentType: "application/json", dataType: "json", ...

What are the differences between using .val() and .innerHTML?

When working with JQuery and trying to access elements, I have noticed that the method for retrieving content differs depending on the element type. For example, if I have a form with a textarea and want to get the text inside of it, I would use $("textare ...

Utilizing a Link element in conjunction with ListItem and Typescript for enhanced functionality

I am currently using material-ui version 3.5.1 My goal is to have ListItem utilize the Link component in the following manner: <ListItem component={Link} to="/some/path"> <ListItemText primary="Text" /> </ListItem> However, when I tr ...

Alert: Every child within a list must be assigned a distinct "key" property in React.js

After reading the article on looping inside React JSX, I decided to enhance my code by rendering components through a loop. However, an issue has arisen in the form of a warning message: Warning Each child in a list should have a unique "key" pro ...

What is the process for manually assigning a value to a variable in a test within the Jest framework?

app.test.js In my jest file, I have the code snippet below: 'use strict'; const request = require('supertest'); const app = require('./app'); //https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascrip ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

Rearrange and place items at the dropped location

I am looking to create a drag-and-drop feature for moving items from a list of products to an empty container. Upon completion, I need to save the location and the selected items in a database so that I can recall this layout later. However, I have encoun ...

Convince me otherwise: Utilizing a Sinatra API paired with a comprehensive JS/HTML frontend

As I embark on the journey of designing a social website that needs to support a large number of users, I have come up with an interesting approach: Implementing Sinatra on the backend with a comprehensive REST API to handle all operations on the website ...

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...