Skip to content

Commit ff5adcb

Browse files
committed
Initial commit
0 parents  commit ff5adcb

23 files changed

+4861
-0
lines changed

.babelrc

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"presets": [
3+
"env",
4+
"es2017"
5+
],
6+
"plugins": ["transform-runtime"]
7+
}

.eslintrc

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"extends": "airbnb-base",
3+
"rules": {
4+
"import/prefer-default-export": 0,
5+
"arrow-parens": [
6+
"error",
7+
"always"
8+
]
9+
},
10+
"env": {
11+
"jest": true
12+
}
13+
}

.gitignore

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# modules
2+
node_modules
3+
npm-debug.log
4+
5+
# generated
6+
coverage
7+
.nyc*
8+
*.log
9+
*.cache
10+
.eslintcache
11+
package-lock.json
12+
13+
# macOS
14+
.DS_STORE
15+
16+
# IDE / Editors
17+
.idea/
18+
19+
# babel transformed
20+
lib

.npmignore

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
coverage
2+
test
3+
.babelrc
4+
.eslintrc
5+
.gitignore
6+
.travis.yml
7+
yarn.lock
8+
package-lock.json
9+
src

.travis.yml

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
language: node_js
2+
sudo: true
3+
dist: trusty
4+
node_js:
5+
- 6
6+
- 8
7+
install:
8+
- yarn
9+
- npm i -g codecov
10+
script:
11+
- npm test
12+
notifications:
13+
email:
14+
on_failure: change
15+
after_success:
16+
- codecov

.vscode/launch.json

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
// macOS compatible:
8+
{
9+
"type": "node",
10+
"request": "launch",
11+
"name": "Jest Current Test",
12+
"program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
13+
"args": [
14+
"${file}"
15+
]
16+
}
17+
]
18+
}

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018-present Lukas Aichbauer
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# convert-array-to-csv
2+
3+
[![npm](https://img.shields.io/npm/v/convert-array-to-csv.svg?style=flat-square)](https://www.npmjs.com/package/convert-array-to-csv)
4+
[![Travis branch](https://img.shields.io/travis/aichbauer/node-convert-array-to-csv/master.svg?style=flat-square)](https://travis-ci.org/aichbauer/node-convert-array-to-csv)
5+
[![Codecov branch](https://img.shields.io/codecov/c/github/aichbauer/node-convert-array-to-csv/master.svg?style=flat-square)](https://codecov.io/gh/aichbauer/node-convert-array-to-csv)
6+
7+
> Convert an array to a csv formatted string
8+
9+
## Table of Contents
10+
11+
* [Why?](#why)
12+
* [Installation](#installation)
13+
* [Functions](#functions)
14+
* [Usage](#usage)
15+
* [License](#license)
16+
17+
## Why?
18+
19+
I needed a simple way to download the data from a table component in a csv format.
20+
21+
## Installation
22+
23+
```sh
24+
$ npm i convert-array-to-csv -S
25+
```
26+
27+
or
28+
29+
```sh
30+
$ yarn add convert-array-to-csv
31+
```
32+
33+
## Functions
34+
35+
Take a look into the [usage section](#usage) for a detailed example.
36+
37+
### convertArrayToCSV
38+
39+
> Note: you can also use the default export.
40+
41+
This function converts an array of objects, or an array of arrays into an csv formatted string.
42+
43+
#### Syntax
44+
45+
Returns a new string.
46+
47+
```js
48+
const csv = convertArrayToCSV(data, options);
49+
```
50+
51+
##### Parameters
52+
53+
* data: an array of arrays or an array of objects
54+
* options: a object
55+
* holds two keys: header and separator
56+
* **header**: and array with the name of the columns, default: `undefined`
57+
* **separator**: the character which is the separator in your csv formatted string, default: `','`
58+
59+
## Usage
60+
61+
An example how to use it.
62+
63+
```js
64+
const { convertArrayToCSV } = require('convert-array-to-csv');
65+
const converter = require('convert-array-to-csv');
66+
67+
const header = ['number', 'first', 'last', 'handle'];
68+
const dataArrays = [
69+
[1, 'Mark', 'Otto', '@mdo'],
70+
[2, 'Jacob', 'Thornton', '@fat'],
71+
[3, 'Larry', 'the Bird', '@twitter'],
72+
];
73+
const dataObjects = [
74+
{
75+
number: 1,
76+
first: 'Mark',
77+
last: 'Otto',
78+
handle: '@mdo',
79+
},
80+
{
81+
number: 2,
82+
first: 'Jacob',
83+
last: 'Thornton',
84+
handle: '@fat',
85+
},
86+
{
87+
number: 3,
88+
first: 'Larry',
89+
last: 'the Bird',
90+
handle: '@twitter',
91+
},
92+
];
93+
94+
/*
95+
const csvFromArrayOfObjects = 'number,first,last,handle\n1,Mark,Otto,@mdo\n2,Jacob,Thornton,@fat\n3,Larry,the Bird,@twitter\n';
96+
*/
97+
const csvFromArrayOfObjects = convertArrayToCSV(dataObjects);
98+
99+
/*
100+
const csvFromArrayOfArrays = 'number;first;last;handle\n1;Mark;Otto;@mdo\n2;Jacob;Thornton;@fat\n3;Larry;the Bird;@twitter\n';
101+
*/
102+
const csvFromArrayOfArrays = convertArrayToCSV(dataArrays, {
103+
header,
104+
separator: ';'
105+
});
106+
```
107+
108+
## License
109+
110+
MIT © Lukas Aichbauer

package.json

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
{
2+
"name": "convert-array-to-csv",
3+
"version": "0.0.0",
4+
"description": "Convert an array to a csv formatted string",
5+
"main": "./lib/index.js",
6+
"repository": "https://www.github.com/aichbauer/node-convert-array-to-csv",
7+
"author": "Aichbauer Lukas <[email protected]>",
8+
"license": "MIT",
9+
"private": false,
10+
"scripts": {
11+
"pretest": "npm run build && npm run lint",
12+
"lint": "eslint src",
13+
"test": "jest --coverage",
14+
"build": "babel src --out-dir lib",
15+
"prepublish": "npm run build"
16+
},
17+
"keywords": [
18+
"array",
19+
"csv",
20+
"list",
21+
"convert",
22+
"comma-separated",
23+
"values",
24+
"convert-array-to-csv"
25+
],
26+
"jest": {
27+
"globals": {
28+
"__DEV__": true
29+
},
30+
"testEnvironment": "node",
31+
"testPathIgnorePatterns": [
32+
"/node_modules/"
33+
]
34+
},
35+
"devDependencies": {
36+
"babel-cli": "^6.26.0",
37+
"babel-plugin-transform-runtime": "^6.23.0",
38+
"babel-preset-env": "^1.6.1",
39+
"babel-preset-es2017": "^6.24.1",
40+
"eslint": "^4.19.1",
41+
"eslint-config-airbnb-base": "^12.1.0",
42+
"eslint-plugin-import": "^2.9.0",
43+
"jest": "^22.4.3"
44+
}
45+
}

src/helpers/check-if-valid.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const checkIfValid = (data) => {
2+
if (!Array.isArray(data)) {
3+
throw new Error(`data has to be typeof: ${typeof []} and instanceof Array: ${[] instanceof Array} but got typeof: ${typeof data} and instanceof Array: ${data instanceof Array}`);
4+
}
5+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
export const checkSpecialCharsAndEmpty = (value) => {
2+
const thisValue = value.toString().toLowerCase();
3+
4+
const hasSpecialChars =
5+
thisValue.includes('\n') ||
6+
thisValue.includes('\t') ||
7+
thisValue.includes(',') ||
8+
thisValue.includes(';') ||
9+
thisValue.includes('.') ||
10+
thisValue.includes('"') ||
11+
thisValue.includes('\'') ||
12+
thisValue.includes('`') ||
13+
thisValue.includes('´') ||
14+
thisValue.length === 0;
15+
16+
return hasSpecialChars;
17+
};

src/index.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { checkIfValid } from './helpers/check-if-valid';
2+
import { convertArrayOfArraysToCSV } from './modules/convert-array-of-arrays-to-csv';
3+
import { convertArrayOfObjectsToCSV } from './modules/convert-array-of-objects-to-csv';
4+
5+
export const convertArrayToCSV = (data, { header, separator }) => {
6+
checkIfValid(data);
7+
8+
const thisOptions = {
9+
header: header || undefined,
10+
separator: separator || ',',
11+
};
12+
13+
if (Array.isArray(data[0])) {
14+
return convertArrayOfArraysToCSV(data, thisOptions);
15+
}
16+
17+
return convertArrayOfObjectsToCSV(data, thisOptions);
18+
};
19+
20+
export default convertArrayToCSV;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { checkSpecialCharsAndEmpty } from '../helpers/check-special-chars-and-empty';
2+
3+
export const convertArrayOfArraysToCSV = (data, { header, separator } = {}) => {
4+
const array = [...data];
5+
let csv = '';
6+
7+
if (header) {
8+
header.forEach((headerEl, i) => {
9+
const includesSpecials = checkSpecialCharsAndEmpty(headerEl);
10+
csv +=
11+
(includesSpecials ? `"${headerEl}"` : headerEl) +
12+
(Object.entries(header).length - 1 === i ? '' : separator) +
13+
(Object.entries(header).length - 1 === i ? '\n' : '');
14+
});
15+
}
16+
17+
array.forEach((row) => {
18+
row.forEach((value, i) => {
19+
const includesSpecials = checkSpecialCharsAndEmpty(value);
20+
csv +=
21+
(includesSpecials ? `"${value}"` : value) +
22+
(row.length - 1 === i ? '' : separator) +
23+
(row.length - 1 === i ? '\n' : '');
24+
});
25+
});
26+
27+
return csv;
28+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { checkSpecialCharsAndEmpty } from '../helpers/check-special-chars-and-empty';
2+
3+
export const convertArrayOfObjectsToCSV = (data, { header, separator } = {}) => {
4+
const array = [...data];
5+
let csv = '';
6+
7+
if (header) {
8+
header.forEach((headerEl, i) => {
9+
const includesSpecials = checkSpecialCharsAndEmpty(headerEl);
10+
csv +=
11+
(includesSpecials ? `"${headerEl}"` : headerEl) +
12+
(Object.entries(header).length - 1 === i ? '' : separator) +
13+
(Object.entries(header).length - 1 === i ? '\n' : '');
14+
});
15+
}
16+
17+
array.forEach((row, idx) => {
18+
if (!header && idx === 0) {
19+
Object.entries(row).forEach((entry, i) => {
20+
const key = entry[0];
21+
const includesSpecials = checkSpecialCharsAndEmpty(key);
22+
23+
csv +=
24+
(includesSpecials ? `"${key}"` : key) +
25+
(Object.entries(row).length - 1 === i ? '' : separator) +
26+
(Object.entries(row).length - 1 === i ? '\n' : '');
27+
});
28+
}
29+
Object.entries(row).forEach((entry, i) => {
30+
const value = entry[1];
31+
const includesSpecials = checkSpecialCharsAndEmpty(value);
32+
33+
csv +=
34+
(includesSpecials ? `"${value}"` : value) +
35+
(Object.entries(row).length - 1 === i ? '' : separator) +
36+
(Object.entries(row).length - 1 === i ? '\n' : '');
37+
});
38+
});
39+
40+
return csv;
41+
};

0 commit comments

Comments
 (0)