这是一个函数,它将数组作为参数并将其转换为JSON(键值)对象
csvToJSON(array): any {
let arr = {};
let keys = ["companyName", "companyNumber", "companyDescription"];
for (var i = 0; i < array.length; ++i) {
arr[keys[i]] = array[i];
}
return arr;
}
这是调用函数
onSubmit() {
this.papa.parse(this.csvFile, {
step: function (row) {
var jsonObj = this.csvToJSON(row.data[0]);
console.log(jsonObj);
}
});}
我使用papaparse读取CSV文件将其转换为数组,然后转到csvtoJSON函数成为json对象。但是当我运行该函数时,它会显示错误
&#34;错误类型错误:无法读取未定义的属性csvToJSON&#34;
编辑:使用箭头功能解决了问题。
答案 0 :(得分:1)
您正在使用TypeScript,您可以使用arrow function expression
,它会保留this
的值。
onSubmit() {
this.papa.parse(this.csvFile, {
step: (row) => {
var jsonObj = this.csvToJSON(row.data[0]);
console.log(jsonObj);
}
});}
答案 1 :(得分:0)
您还可以通过构造函数中的csvToJSON
方法将.bind
方法绑定到对象实例的实例
this.csvToJSON = this.csvToJSON.bind(this);
当您使用数组函数时,系统会自动创建property
bind
实例,但您不能覆盖已交付类中的属性而不是方法。