Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda