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

Allow custom function to map columns

Open sbehrends opened this issue 6 years ago • 0 comments

columns option now supports either boolean or function. This function is responsable to map the array of keys of the first column. It receives an array of strings and should return an array of strings.

A simple example would be to lower case the name of the columns

const csv = require('csv-streamify')
const parser = csv({
  columns: (cols) => cols.map(col => col.toLowerCase()),
})

Another example would be to clean strange characters from row title (like required on https://github.com/klaemo/csv-stream/issues/53)

const csv = require('csv-streamify')
const parser = csv({
  columns: (cols) => cols.map(col => col.replace(/[^a-zA-Z0-9_]/g,'')),
})

it also covers the proposed in https://github.com/klaemo/csv-stream/pull/40 without the need of creating a new option

const parser = csv({
  columns: (cols) => cols.map(name => {
    switch (name) {
      case 'some Weird Name':
        return 'new_name'
      default:
        return name
    }
  })
})

sbehrends avatar Feb 13 '19 23:02 sbehrends