Npm csv-parser: skip header line, return array of objects?
I am working with the csv-parse module in npm to upload a CSV file via Ajax. I want to read it into an array of objects.
Here is the CSV file I'm working with:
val,row_id,date,row_name
19378.02,10Q,2013-10-01,NHS Oxfordshire
14104.81,01M,2014-01-01,NHS North Manchester
11130.65,09D,2014-09-01,NHS Brighton & Hove
3611.32,08J,2014-11-01,NHS Kingston
And here is my code:
$.ajax({
type: "GET",
url: _this.globalOptions.numeratorUrl,
error: function() {
// show error
},
success: function(data) {
parse(data,
{columns: ['val','row_id','date','row_name'] },
function(err, output){
console.log('parsed', output);
}
);
}
This works, but there are two things I would like to improve:
- By default, it includes the title bar, so
output[0]
is as follows:{ 'val': 'val', 'row_id': 'row_id', ...}
. Is there a way that I can automatically skip the title bar? - I don't like that I have to define explicitly
columns
in order to create an array of objects. Column name and order may vary. Is there a way that I can automatically use the values ββfrom the header row, whatever they are?
+3
source to share
1 answer
from the documentation, at the link:
columns (array | boolean | function) A list of fields as an array, a user-defined callback that takes the first row and returns the column names or true if autodiscovered in the first CSV line
, by default, null, affects the result dataset in the sense that records will be objects instead of arrays.
and this is the answer, so
$.ajax({
type: "GET",
url: _this.globalOptions.numeratorUrl,
error: function() {
// show error
},
success: function(data) {
parse(data,
{columns: true },
function(err, output){
console.log('parsed', output);
}
);
}
+2
source to share