Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Created January 21, 2022 15:16
Show Gist options
  • Save andyrichardson/d22a5199afc0c989b76394d612a2b49f to your computer and use it in GitHub Desktop.
Save andyrichardson/d22a5199afc0c989b76394d612a2b49f to your computer and use it in GitHub Desktop.
JSON <-> CSV conversion

csvToJson

const csvToJson = (arr: any[]) => {
  const keys = Object.keys(arr[0])
  return arr.reduce(
    (p, c) => `${p}\n${keys.map((k) => c[k]).join(',')}`,
    keys.join(','),
  )
}

jsonToCsv

const jsonToCsv = (str: string) => {
  const rows = str.split('\n')
  const keys = rows[0].split(',')
  return rows.slice(1).reduce<any>(
    (p, c) => [
      ...p,
      c.split(',').reduce(
        (pp, cc, i) => ({
          ...pp,
          [keys[i]]: cc,
        }),
        {},
      ),
    ],
    [],
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment