最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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!

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!

Share Improve this question asked Mar 4, 2018 at 17:43 ThePat02ThePat02 171 gold badge1 silver badge7 bronze badges 1
  • 1 Possible duplicate of NodeJs reading csv file – Hassan Imam Commented Mar 4, 2018 at 18:03
Add a ment  | 

1 Answer 1

Reset to default 1

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 mas 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 bee 1 string

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

Hope these help!

发布评论

评论列表(0)

  1. 暂无评论