Home > Net >  Javascript/TypeScript - Can I add class properties from an array?
Javascript/TypeScript - Can I add class properties from an array?

Time:02-15

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!

CodePudding user response:

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;
  • Related