Closed ScottChapman closed 5 years ago
The below snippet, setting field ids to header
, works fine for me. Do you mind sharing me a code example that is not working for you?
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
path: 'file.csv',
header: ['name', 'lang']
});
const records = [
{name: 'Bob', lang: 'French, English'},
{name: 'Mary', lang: 'English'}
];
csvWriter.writeRecords(records);
Bob,"French, English"
Mary,English
But code shows this: https://github.com/ryu1kn/csv-writer/blob/master/lib/csv-stringifiers/object.js#L17
That line is checking if the header is available, by checking if the item of header
array is an object.
If you don't want to write a header line, don't give title to header elements and just give field IDs as a string.
cf. README
@ryu1kn - right, and it returns null
if the item is NOT an object. Your example actually also does not work properly. You'll notice that there is no header saved to the file. Try replacing the header with this and you'll see the difference:
const csvWriter = createCsvWriter({
path: 'file.csv',
header: [
{id: 'name', title: "Name"},
{id: 'lang', title:"Lang"}
]
});
If the behavior is intentional, then I think it should be documented as such. But my expectation was that the array of strings would mean that the field id
and title
were the same for each field.
Well, no header row if you just give field ids IS the expected behaviour as I quoted in my second comment from README.
If you don't want to write a header line, don't give title to header elements and just give field IDs as a string.
cf. README
If you want field IDs as a header, you need to repeat your self, like:
header: [
{id: 'name', title: 'name'},
{id: 'lang', title: 'lang'}
]
I see, is it just used for validation then?
It is used for deciding column ordering. header: ['name', 'lang']
prints name
column first followed by lang
, whereas header: ['lang', 'name']
prints lang
first.
Documentation:
But code shows this: https://github.com/ryu1kn/csv-writer/blob/master/lib/csv-stringifiers/object.js#L17