Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Javascript/TypeScript - Can I add class properties from an array?

Thank you for the help in advance. I am working in TypeScript, I'd assume any JS solution also works. I'd like to make something like this:

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 trying to use it with the 'xlsx' module to export project data into an Excel sheet. It is necessary for this module that it is a class, rather than several arrays. I could type it out manually, but there is 7 properties for every item and this would be very ugly code. It is also possible that I am later asked to add more items. If it were Python, I could do something like this bc classes and dictionaries are different things:

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

What is a Typescript alternative?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It is possible that you are looking for index-signatures. In JavaScript/Typescript objects are more comparable to Python dictionaries than classes, and for data stores such as this, I would recommend them.

You can create your desired data store and access its properties like so:

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

const data: ExcelData = {};

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

It seems odd to want to have "Quantity-*" as a property though. A structure that uses ids to lookup and set quantities would look like this:

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

const data: ExcelData = {};

data.someId = 69;

Lastly, you can do what you are trying to do with a class like so:

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

const myInstance = new MyClass();

myInstance.id1 = "123-420";
myInstance.quantity1 = 69;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!