Title says the question but to be more specific and using an example given:
- | Name | Surname | Age |
- | Robert | Red | 25
and I want to use the name Robert in the code like a variable but to export it from the CSV file. (so something like csv.name[1]) I've been studying for 2/3 months now so I'm totally a beginner. I've been searching online or in forums but couldn't find anything. Let me know if there's something confusing. Have a wonderful day all.
Edit* and then you can do like
- var name = csv.name[1]
- console.log(name)
And by editing the name automatically will change the output.
CodePudding user response:
Since this post is tagged with node.js, I'm going to assume that you are actually using it.
Javascript doesn't have any built-in ways to directly access rows and columns from a csv file. You have to firstly parse the csv file into a type which Javascript can understand.
That being said, your best bet might be installing the following npm package (or just the csv-parse subpackage).
If you don't want to install additional npm packages, take a look at this answer. It's a simple Javascript function that allows you to parse a csv file into an array which you can access like you mentioned in your question (array[row][column]).
CodePudding user response:
You might look at d3-dsv (delimiter seperated values) part of the d3 library.
const csvInput = "Name,Surname,Age\nRobert,Red,25\nJudith,Gray,29"
const parsed = d3.csvParse(csvInput);
console.log(parsed[0].Name);
console.log(parsed);
<script src="https://cdn.jsdelivr.net/npm/d3-dsv@3"></script>
