Snippet - Shallow object to CSV

4 years ago
const os = require('os')

const objectToCsv = obj =>
  Object.keys(obj)
    .map(key => '"' + (obj[key] ? obj[key].replace(/\"/g, '""') : '') + '"')
    .join(',')

const objectArrayToCsv = objArray => {
  if (objArray.length) {
    let lines = Object.keys(objArray[0]).join(',') + os.EOL
    lines += objArray.map(objectToCsv).join(os.EOL)
    return lines
  } else {
    console.log('Array is empty')
    return ''
  }
}

const csv = objectArrayToCsv([
  { firstName: 'john', lastName: 'doe', id: 1 },
  { firstName: 'jane', lastName: 'smith', id: 2 },
  { firstName: 'bob', lastName: 'jones', id: 3 }
])

console.log(csv)
Discuss on Twitter