简体   繁体   中英

Reading a .csv file in Javascript line by line and put it into an array using a while loop

I have done this in C# before, but I don't have a clue how to do that in javascript.

What I want to do:

while (/*Is not the last line of the csv file*/)
 {
    var text = /* read the line */
    var split = /* array with the values from the line that was read */

    alert(split[0]);
}

Thank you for your suggestions!

Is your CSV file stored somewhere? Or do you have it stored as a string?

To follow your structure, here is a plunker: https://plnkr.co/edit/dCQ4HRz3mCTkjFYrkVVA?p=preview

var csv = 
`data1,data2,data3
col1,col2,col3`;
var lines = csv.split("\n");
while( typeof lines[0] !== "undefined" ){
    var line = lines.shift();
    var split = line.split(',');
    document.querySelector("#content").innerHTML += split[0]+"<br/>";
}

If you haven't got the CSV as a string, depending on if you are using Node to read a file or JavaScript in the browser to read an uploaded file, you need other code to convert that. Or you may use a library.

You may have to handle trimming of spaces around commas by modifying the code above.

By the way, instead of creating temporary variables, some may prefer not using a while-loop: https://plnkr.co/edit/31yMTw9RepdW1cF8I6qj?p=preview

document.querySelector("#content").innerHTML = 
csv.split("\n")        // these are lines
  .map(                // map those lines, 1 line to ...
    l => l.split(",")  // to 1 array
  ).map(
    a => a[0]+"<br/>"  // and map those arrays 1 array to the string
  ).join('');            // and join them to become 1 string

You may find those array manipulating functions interesting, like map() , filter() , reduce() .

Hope these help!

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