Is it possible to dynamically assign class properties from an array in JavaScript/TypeScript?

Greetings for the assistance in advance. Currently, I am working with TypeScript, but I believe any JS solution will suffice. I aim to create something akin to the following:

class ExcelData {
  'Id 1': items[0].id,
  'Quantity 1': items[0].quantity,
  'Id 2': items[1].id,
  'Quantity 2': items[1].quantity
  //...
  'Id 40': items[39].id,
  'Quantity 40': items[39].quantity,
}

I am endeavoring to utilize it with the 'xlsx' module to export project data into an Excel spreadsheet. The module mandates this be a class rather than multiple arrays. While I could manually input the data, with 7 properties per item, the code would become quite messy. Moreover, there may be a requirement to include additional items in the future. In Python, I could achieve a similar result as classes and dictionaries are distinct entities:

excel_data = {}
for i in range (40):
  excel_data['Id '+ str(i)] = items[i].id
  excel_data['Quantity '+ str(i)] = items[i].quantity

Is there a TypeScript alternative that can serve this purpose?

Many thanks!

Answer №1

If you're in search of a solution related to index-signatures, consider using objects in JavaScript/Typescript similar to Python dictionaries rather than classes, especially for data storage.

To create and access your desired data store, follow this example:

interface ExcelData {
    [property: string]: string | number | undefined;
}

const data: ExcelData = {};

data.id1 = "123-420";
data.quantity1 = 69;

You may want to rethink having properties like "Quantity-*". A better structure that uses ids to manage quantities could be implemented like so:

interface ExcelData {
    [id: string]: number | undefined;
}

const data: ExcelData = {};

data.someId = 69;

Alternatively, if needed, you can achieve your goal using a class as shown below:

class MyClass {
    [property: string]: string | number | undefined;
}

const myInstance = new MyClass();

myInstance.id1 = "123-420";
myInstance.quantity1 = 69;

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

Ajax: client dilemma created by the interaction of two functions

My university homework assignment requires me to develop a small e-commerce website. After logging in, the user will be directed to the homepage where they will receive a JSON object from the server containing product information to dynamically generate th ...

Show the current temperature data retrieved from the weather API

I'm trying to figure out what's causing the issue with the temperature not displaying. Can anyone help me identify and fix the error? <script type="text/javascript"> $.ajax({ url: 'https://api.weather.gov/gridpoints/EWX ...

Struggles with jquery and fixing images

I am currently working on a project where users can click on a thumbnail image to display a larger version in the main image section. $('.alternative_images a').click(function(e){ var imgSrc = $(this).attr('href'); $('.mai ...

Typescript: requirement appears to be unmet

While compiling my Angular project, I encountered an error related to a package installed via NPM: node_modules/astrocite-ris/index.d.ts:36:39 - error TS2503: Cannot find namespace 'CSL'. The package named Astrocite contains a subpackage calle ...

Building Dynamic Forms with React.js and Bootstrap for Easy Input Field Management

In the process of developing a web application using React.js and react-bootstrap, I encountered an interesting challenge. On one of the form pages, users should be able to input symptoms of an illness they are dealing with. The key functionality required ...

What could be causing my ng-grid footer to refuse to align with the bottom border?

Currently utilizing ng-grid and various AngularJS UI Bootstrap components on my website, I have encountered a recurring issue. By diligently investigating, I have successfully replicated the problem. Access the Plunker demonstration through this link. The ...

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

Struggling to grasp the concept of duplicating the Three.js Editor Import feature

For the past few hours, I've been struggling to understand how I can create a .js importer similar to the functionality in the Three.js Editor. I want users to be able to easily load a .js file from a 'file load' pop-up. Despite searching o ...

What is the best way to eliminate all occurrences of a specific element within an array?

I'm currently facing an issue with my code - it's supposed to remove all instances of a certain item from an array, but it's not working as expected. Can anyone help me identify what I'm doing wrong? let nums = [1, 90, 90, 1123, 90, ...

Create a fake version of ElementRef and simulate the getBoundingClientRect() function

Looking to simulate ElementRef and access getBoundingClientRect() I experimented with the code below, but it didn't yield the expected results. const mockHostRef = { nativeElement: { getBoundingClientRect: {top: 10, left: 10} } } {pr ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Retrieve the value of the second child element in a table cell when clicking on it with Javascript

I have created a table with one row that includes the title of the month and a cell containing an inner table with multiple rows and cells. I want to display the content of the second cell in the second table as a modal box or alert dialog when it is click ...

Ways to conceal sidebar after user logs out and reveal sidebar upon user's successful login?

Currently, I am utilizing the Dashgum bootstrap template obtained from Gridgum for a specific assignment. The task involves displaying the side navbar for logged-in users persistently, even after they have closed the site, and hiding the side navbar comple ...

Storing data from a massive JSON array into a separate array using a specific condition in JavaScript

Dealing with a large JSON array can be challenging. In this case, I am looking to extract specific objects from the array based on a condition - each object should have "dbstatus":-3. data = [{"id":"122","dbstatus":-3},{"id":"123","dbstatus":"-6"},{"id" ...

PyScript <script type="py-editor"> Issue: SharedArrayBuffer cannot be used in an insecure environment

I am currently using PyScript to execute a basic Python script within my HTML file in order to show a pandas DataFrame. However, upon loading the page in the browser and attempting to run the code block by clicking the run button, I encounter an error rela ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

Tips for creating a dynamic curved SVG path

I'm looking to draw a black border only along the inside of this SVG. I've tried adding stroke and setting the stroke-width, but that applies the border to the entire SVG. Is there a way to limit the stroke to a certain point within the SVG? d ...

An error occurred when trying to pass JSON data to the view in the "orchard" framework: TypeError - e.slice is not a function

public ActionResult Grouping() { return View(); } public ActionResult Read([DataSourceRequest] DataSourceRequest request, string text) { var result = _auto.Table.ToList().Where(s => s. ...

I am facing an issue with my React/Redux API where it is not logging out correctly and displaying [[

As a beginner in the coding world, I've run into some challenges while working with a React/Redux API. Following along with Bucky Roberts' YouTube tutorial, I decided to replace his static names object with an API that I then integrate into my r ...