Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda