objects2csv

1.1.0 • Public • Published

objects2csv

A simple, small library to convert JavaScript objects into a csv string.

npm version

Features

  • Small (~5kB unpacked)
  • No dependencies
  • Uses modern JavaScript (ES7)
  • Automatic field detection
  • Default value for missing fields
  • Custom & automatic quotation (can be disabled)
  • Custom csv separator, line separator and escape sequence
  • Excludable fields

Installation

npm install objects2csv

Usage

const convert = require('objects2csv');

const data = [
    {type: "car", model: "BMW", year: 2019, maxPassengers: 5, doors: 5},
    {type: "car", model: "VW", year: 2003, doors: 3},
    {type: "bus", model: "Mercedes", year: 2019, maxPassengers: 50},
]

const csv = convert(data);

console.log(csv);

Output:

"type";"model";"year";"maxPassengers";"doors"
"car";"BMW";"2019";"5";"5"
"car";"VW";"2003";" ";"3"
"bus";"Mercedes";"2019";"50";" "

This will use the default values for all options. In order to customize the generated csv, the following options exist:

// These options represent the default values
const options = {
    header: true, // If false, the header won't be included in the converted string
    unavailable: " ", // If the value does not exist, this is the string that will be used instead
    separator: ";", // This is the sequence that will be used as a separator (between each value)
    quote: "\"", // This is the sequence that will be used to quote the values, for example: "myValue"
    escape: "\\", // This is the sequence that will be used to escape a sequence in the value, if it is equal to the quote, for example: "And then he said \"Hello\""
    lineSeparator: "\n", // This is the sequence that will be used at the end of a line (after each object)
    excludeKeys: [] // If you don't want a field to be in the final csv string, exclude it here. For example the ccnumber and cvv field: ["ccnumber", "cvv"]
}

Usage of the custom options:

const csv = convert(data, { excludeKeys: ["maxPassengers", "doors"], quote: null }); // quote: "" can also be used

Output:

type;model;year
car;BMW;2019
car;VW;2003
bus;Mercedes;2019

Package Sidebar

Install

npm i objects2csv

Weekly Downloads

11

Version

1.1.0

License

MIT

Unpacked Size

5.01 kB

Total Files

4

Last publish

Collaborators

  • htlfabian