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
1 Answer
Reset to default 1Is 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!
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745473716a4629248.html
评论列表(0条)