array-csv
v1.1.0
Published
Convert various arrays to CSV and CSV to arrays
Downloads
1
Readme
array-csv
Array-csv is a Javascript library for dealing with arrays and csv.
Installation
Use npm to install package.
npm install array-csv
Usage
If you want, you can check documentation.
Array of objects to CSV
options: writeHeader, keys
- writeHeader: default true, if true writes objects keys for first row
- keys: default [], if empty array it will write all object keys, otherwise you can specify the keys you want written such as ["a", "b"]
Write all object properties to csv
const arrayCsv = require("array-csv");
const array = [{name: "John", age: 10, id: 1}, {name: "Alice", age: 30, id: 2}];
arrayCsv.arrayOfObjectsToCsv(array, "people.csv");
// output people.csv
// name,age,id
// John,10,1
// Alice,30,2
Write only specified properties to csv
const arrayCsv = require("array-csv");
const array = [{name: "John", age: 10, id: 1}, {name: "Alice", age: 30, id: 2}];
arrayCsv.arrayOfObjectsToCsv(array, "people.csv", {keys: ["name", "age"]});
// output people.csv
// name,age
// John,10
// Alice,30
Do not write header row as first row
const arrayCsv = require("array-csv");
const array = [{name: "John", age: 10, id: 1}, {name: "Alice", age: 30, id: 2}];
arrayCsv.arrayOfObjectsToCsv(array, "people.csv", {writeHeader: false});
// output people.csv
// John,10,1
// Alice,30,2
2d array to CSV
options: writeHeader, hasHeader
- writeHeader: default true, if true writes objects keys for first row
- hasHeader: default true, if array
Write 2d array to CSV, all properties
2d array to CSV does not support filtering columns to be written. It always writes all properties.
If first inner array is not header you have to specify this with hasHeader: false
options or else the first row will be false.
const arrayCsv = require("array-csv");
const arrayWithHeader = [["a", "b"], [1, 2], [3, 4]];
const arrayWithoutHeader = [[1,2], [3,4]];
arrayCsv.array2dToCsv(arrayWithHeader, "test.csv");
// output test.csv
// a,b
// 1,2
// 3,4
arrayCsv.array2DToCsv(arrayWithoutHeader, "test.csv", {hasHeader: false});
// output test.csv
// 1,2
// 3,4
arrayCsv.array2DToCsv(arrayWithoutHeader, "test.csv"); // missing first row 1,2
// output test.csv
// 3,4
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.