首页 > 解决方案 > 如何在 TypeScript 中将对象从硬编码更改为动态属性

问题描述

在 Visual Studio MVC 应用程序中使用 TypeScript 2.2 和 Angular,我有一个对象(“标题”),用于存储一组数据的标题名称。该对象当前已在高级中进行硬编码。我需要将其更改为根据数据动态填充。最终,这些数据被导出为 CSV。目前,代码类似于以下内容:

let output = (this.allData);
let headers = {};
let formattedItems = [];
let csvData: any;
let fileName = "file.xls";
headers = {
   customerName = "CustomerName",
   productName1 = "Product Name 1",  
   productName2 = "Product Name 2",
   monthYear = "Month/Year"   
};
output.forEach((item) => {
     formattedItems.push ({
     customerName:  (item.Id > 0 ) ? item.Name : '',     
     productName1:  (item.Id > 0 ) ? item.Count : '',     
     productName2:  (item.Id > 0 ) ? item.Count : '',   
     monthYear:   (item.Id > 0 ) ? item.SaleDate: '',  
  });
});
csvData = this.exportCsv(headers, formattedItems);
this.exportCSV(csvData, fileName);

我需要修改代码以执行以下操作:

  1. 循环遍历数据
  2. 首先,获取列名
  3. 其次,相应地附加数据行

    headers = { customerName = "CustomerName", // if (columnName like "Product") // 然后创建新的列名;monthYear = "月/年"
    };

生成的文件将从只有两个“产品名称”列发生变化:

|客户名称| 耐克鞋 | 阿迪达斯鞋 | 2012年3月

到可变数量的“产品名称”列:

|客户名称| 耐克鞋 | 阿迪达斯鞋 | 锐步鞋 | 新百伦鞋| 2012年3月

标签: angulartypescript

解决方案


I ended up changing headers to an array then dynamically added the data to the end of the array:

let headers = [];
headers = ['CustomerName', 'Month/Year' ]
output.forEach((item) => {
    formattedItems.push ({
    customerName:  (item.Id > 0 ) ? item.Name : '',          
    monthYear:   (item.Id > 0 ) ? item.SaleDate: '',  
  });
});
//Dynamically add an extra column for each product
for (let x = 0; itemsFormatted.length > x; x++) {
  for (let y = 0; this.products.length > y; y++) {
      if (x == 0) {
        //Add new header name to array
        headers.push(this.companyOnboarders[y].name);
      }
       //Add data for corresponding header
       itemsFormatted[x][this.products[y].name] = this.products[y].count
   }
}

 csvData = this.exportCsv(headers, formattedItems);
 this.exportCSV(csvData, fileName);

推荐阅读