简体   繁体   中英

How can I skip the first line of items from a CSV?

I am trying to skip over the first line or headers of the items from a CSV in the following function:

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);
  }
}

What would be the best way to do this using Angular or Typescript / Javascript?

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

You was so close! Here is the simple solution via forEach iteration method and join new array items:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM