我试图在以下函数中跳过CSV中项目的第一行或标题:
importFoods() {
var csv= `foodname,category
Banana,Produce
Apple,Produce`;
var lines = csv.split("\n");
console.log('lines',lines);
for(var l in lines) {
var cols = lines[l].split(",")
console.log('cols',cols);
//0 is foodname
//1 is category
var globallistData = {
foodname: cols[0],
category: cols[1],
};
console.log(globallistData)
const globalfoods = this.db.list('/globalfoods');
globalfoods.push(globallistData);
}
}
使用Angular或Typescript / Javascript进行此操作的最佳方法是什么?
答案 0 :(得分:1)
importFoods(){
var csv= `foodname,category
Banana,Produce
Apple,Produce`;
var lines = csv.split("\n");
console.log('lines',lines);
for(var l=1; l<lines.length ;l++){
var cols = lines[l].split(",")
console.log('cols',cols);
//0 is foodname
//1 is category
....
}
}
答案 1 :(得分:0)
你真是太近了!以下是通过forEach
迭代方法和join
个新数组项的简单解决方案:
function importFoods() {
var csv= `foodname,category
Banana,Produce
Apple,Produce`;
var newCsv = [];
var lines = csv.split("\n");
lines.forEach(function(item, i) {
if(i !== 0) newCsv.push(item);
})
newCsv = newCsv.join("\n");
console.log(newCsv);
}
importFoods()