【发布时间】:2020-10-05 07:04:43
【问题描述】:
我尝试在对象数组上加载一个 csv 文件,以将其放入一个带有角度的表格中。
我成功解析了我的 csv 文件并实际获得了这个结构:
this.fileToUpload = files.item(0);
// Parse the file
this.ngxCsvParser.parse(files[0], { header: this.header, delimiter: ';' })
.pipe().subscribe((result: any[]) => {
console.log('Result', result);
//here result is ok,2 lines
result.forEach(row => {
//here how to put my row in a operation object ?
});
this.operations = result;
console.log('operations ' + JSON.stringify(this.operations));
操作日志是:
operations [{"Date operation":"30/09/2020","Date valeur":"01/10/2020","Libelle":"SOUSCRIPTION
PARTS SOCIALES","Debit":"15","Credit":""},{"Date operation":"02/10/2020","Date
valeur":"02/10/2020","Libelle":"TEST","Debit":"","Credit":"1900"}]
问题是如何循环结果以将每一行放入操作对象中?有没有办法在结果中使用列索引?操作对象的结构是这样的:
export class Operation {
date: string;
categorie: string;
libelle: string;
debit: string;
credit: string;
}
我认为 pb 是 csv 文件的第一行不包含与我的操作对象相同的标签。示例:
date operation <> date and libelle <> Libelle ?
感谢您的帮助!
杰夫
编辑:最终解决方案:
onFileChange(files: FileList) {
if (files && files.length) {
this.labelImport.nativeElement.innerText = files.item(0).name;
this.fileToUpload = files.item(0);
// Parse the file you want to select for the operation along with the configuration
this.ngxCsvParser.parse(files[0], {header: this.header, delimiter: ';'})
.pipe().subscribe((result: any[]) => {
this.operations = result.map(resultEntry => mapToOperations(resultEntry));
});
}
function mapToOperations(resultEntry: any) {
const operation = {} as Operation;
operation.date = resultEntry['Date operation'];
operation.credit = resultEntry['Credit'];
operation.libelle = resultEntry['Libelle'];
operation.debit = resultEntry['Debit'];
return operation;
}
【问题讨论】:
标签: arrays angular csv parsing foreach