csv-writer icon indicating copy to clipboard operation
csv-writer copied to clipboard

Replace null with 0

Open mohanraj-r opened this issue 2 years ago • 2 comments

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)

mohanraj-r avatar Dec 22 '23 01:12 mohanraj-r

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

brakmic avatar Jul 16 '24 09:07 brakmic

Imo. to be closed. Should be mapped on higher level, not library itself.

fider avatar Dec 10 '24 11:12 fider