angular - 如何在 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);
我需要修改代码以执行以下操作:
- 循环遍历数据
- 首先,获取列名
其次,相应地附加数据行
headers = { customerName = "CustomerName", // if (columnName like "Product") // 然后创建新的列名;monthYear = "月/年"
};
生成的文件将从只有两个“产品名称”列发生变化:
|客户名称| 耐克鞋 | 阿迪达斯鞋 | 2012年3月
到可变数量的“产品名称”列:
|客户名称| 耐克鞋 | 阿迪达斯鞋 | 锐步鞋 | 新百伦鞋| 2012年3月
解决方案
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);
推荐阅读
- r - 有没有办法从箱线图下方删除空白?
- reactjs - loadash sortBy 应该在遇到 null 时返回
- spring-boot - 无法捕获 ObjectOptimisticLockingFailureException 异常
- amazon-web-services - s3 存储桶 URL 有效,但是当我转到 Cloudfront 托管的实际 URL 时,我的电子邮件表单不起作用,权限问题?
- go - 如何修改对象值的副本而不改变golang中的原始值?
- internet-explorer-11 - 卡片组翻转在旧浏览器中不起作用
- ruby - 处理共享计算机上的权限问题
- typescript - 错误代码 16 和错误:4 DEADLINE_EXCEEDED 与 PubSub Firestore 功能
- javascript - 如何遍历网页上元素的数组值
- r - 如何在函数中添加函数?