问题描述
我尝试将一个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;
}
解决方法
您需要映射结果。
// Parse the file
this.ngxCsvParser.parse(files[0],{ header: this.header,delimiter: ';' })
.subscribe((result: any[]) => {
this.operations = result.map(resultEntry => mapToOperations(resultEntry));
});
mapToOperation
是您需要创建的功能的占位符。此函数接受一个结果条目并使用它创建一个操作对象。