2017-09-28 59 views
1

我試圖跳過下面的函數的第一行或從CSV項目的標題:如何跳過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); 
    } 
} 

什麼是做到這一點使用角或打字稿/ JavaScript中的最佳方式?

+1

'lines.shift()' –

回答

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 
     .... 
    } 
} 
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()