项目作者: aichbauer

项目描述 :
Convert an array to a csv formatted string
高级语言: JavaScript
项目地址: git://github.com/aichbauer/node-convert-array-to-csv.git
创建时间: 2018-04-05T10:48:10Z
项目社区:https://github.com/aichbauer/node-convert-array-to-csv

开源协议:MIT License

下载


convert-array-to-csv

npm
Travis branch
Codecov branch

Convert an array to a csv formatted string

Table of Contents

Why?

I needed a simple way to download the data from a table component in a csv format.

Installation

  1. $ npm i convert-array-to-csv -S

or

  1. $ yarn add convert-array-to-csv

Functions

Take a look into the usage section for a detailed example.

convertArrayToCSV

Note: you can also use the default export.

This function converts an array of objects, or an array of arrays into an csv formatted string.

Syntax

Returns a new string.

  1. const csv = convertArrayToCSV(data, options);
Parameters
  • data: an array of arrays or an array of objects
  • options: a object
    • holds two keys: header and separator
    • header: and array with the name of the columns, default: undefined
    • separator: the character which is the separator in your csv formatted string, default: ','

Usage

An example how to use it.

  1. const { convertArrayToCSV } = require('convert-array-to-csv');
  2. const converter = require('convert-array-to-csv');
  3. const header = ['number', 'first', 'last', 'handle'];
  4. const dataArrays = [
  5. [1, 'Mark', 'Otto', '@mdo'],
  6. [2, 'Jacob', 'Thornton', '@fat'],
  7. [3, 'Larry', 'the Bird', '@twitter'],
  8. ];
  9. const dataObjects = [
  10. {
  11. number: 1,
  12. first: 'Mark',
  13. last: 'Otto',
  14. handle: '@mdo',
  15. },
  16. {
  17. number: 2,
  18. first: 'Jacob',
  19. last: 'Thornton',
  20. handle: '@fat',
  21. },
  22. {
  23. number: 3,
  24. first: 'Larry',
  25. last: 'the Bird',
  26. handle: '@twitter',
  27. },
  28. ];
  29. /*
  30. const csvFromArrayOfObjects = 'number,first,last,handle\n1,Mark,Otto,@mdo\n2,Jacob,Thornton,@fat\n3,Larry,the Bird,@twitter\n';
  31. */
  32. const csvFromArrayOfObjects = convertArrayToCSV(dataObjects);
  33. /*
  34. const csvFromArrayOfArrays = 'number;first;last;handle\n1;Mark;Otto;@mdo\n2;Jacob;Thornton;@fat\n3;Larry;the Bird;@twitter\n';
  35. */
  36. const csvFromArrayOfArrays = convertArrayToCSV(dataArrays, {
  37. header,
  38. separator: ';'
  39. });

License

MIT © Lukas Aichbauer