Search code examples
javascriptfast-csv

Fast-CSV - Reorder columns of array object


I am using fast-csv to generate a CSV file from an array of objects and I would like to change the order of the columns.

I tried setting the headers manually and while they appear in the correct order the headings don't match the column content. I tried using the below:

const header = ['headerA', 'headerC', 'headerB'];
const data = [{"headerA":"itemA", "headerB":"itemB", "headerC":"itemC"}];

const ws = fs.createWriteStream('test.csv');
fastcsv.write(data, { headers: header }).pipe(ws);

The result is:

headerA, headerC, headerB
itemA, itemB, itemC

The examples on the site indicate that this should work or am I missing something?

const csvStream = format({ headers: ['header2', 'header1'] });

csvStream.pipe(process.stdout).on('end', () => process.exit());

csvStream.write({ header1: 'value1a', header2: 'value1b' });
csvStream.write({ header1: 'value2a', header2: 'value2b' });
csvStream.write({ header1: 'value3a', header2: 'value3b' });
csvStream.write({ header1: 'value4a', header2: 'value4b' });
csvStream.end();

Solution

  • After some trial and error I found the following works:

    const { format } = require('@fast-csv/format');
    
    const header = ['headerA', 'headerC', 'headerB'];
    const data = [{"headerA":"itemA", "headerB":"itemB", "headerC":"itemC"}];
    
    const ws = fs.createWriteStream('test.csv');
    
    const csvStream = format({ headers: header, alwaysWriteHeaders: true });
    csvStream.pipe(ws);
    
    data.forEach(row => {
        csvStream.write(row);
    });
    
    csvStream.end()