ryu1kn / csv-writer

Convert objects/arrays into a CSV string or write them into a CSV file
https://www.npmjs.com/package/csv-writer
MIT License
246 stars 39 forks source link

Replace null with 0 #107

Open mohanraj-r opened 10 months ago

mohanraj-r commented 10 months ago

Would it be possible to replace null values with 0 ? It would be the equivalent of the following code from pandas python lib

df = pd.DataFrame.from_records(result)
df = df.fillna(0)
brakmic commented 3 months ago

Hi @mohanraj-r ,

You might want to check out my fork project csv-writer-portable because the original one seems to be abandoned. It should help solve your problem.

Here's a quick code example on how you can use it:

import { createObjectCsvWriter } from 'csv-writer-portable';

const csvPath = 'test.csv';
const csvWriter = createObjectCsvWriter({
  path: csvPath,
  header: [
    { id: 'phone_number', title: 'phone_number' },
    { id: 'name', title: 'name' }
  ],
  filterFunction: (value: any) => {
    if (value === null || value === undefined || value === '') {
      return '0';
    }
    return value;
  },
  alwaysQuote: true,
  quoteEmptyFields: true
});

const data = [
  { phone_number: 9978789799, name: "John Doe" },
  { phone_number: 8898988989, name: "Bob Marlin" },
  { phone_number: undefined, name: "Max Mustermann" },
  { phone_number: null, name: "Jane Doe" },
  { phone_number: "", name: "Dummy User" }
];

async function writeCsv() {
  await csvWriter.writeRecords(data);
}

writeCsv().catch(err => console.error('Error writing CSV:', err));

You can find the npm package here and the GitHub repo here.

Best, Harris