npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

object-to-csv

v1.0.5

Published

Convert array of objects to a CSV. No dependencies.

Downloads

3,856

Readme

object-to-csv

A lightweight, robust & dependency-less Node.js module to convert JSON objects to CSV format.

• Installation

Latest version: 1.0.5

npm install object-to-csv

• Quick Start Example

//1. Import the module
const ObjectToCSV = require('object-to-csv');

//2. Set data
let data = [
    { 
      'make': 'Ford',
      'model': 'Mustang',
      'new': true
    },
];

//3. Set up CSV
let otc = new ObjectToCSV({ data });

//4. Get CSV
let csv = otc.getCSV();

//Outputs:
// "Make","Model","Is The Car New"
// "Ford","Mustang","TRUE"

• Tests

npm test

• Usage

Using the ObjectToCSV module is easy. The setter methods return this which enables chaining functions. Warnings are presented when values are given which may cause issues with the module. Find everything else you need to know below.

• Constructor

The constructor of the ObjectToCSV module allows you to set all of the options up front in key/value format.

Usage Example:

let otc = new ObjectToCSV({
    'keys': [],
    'data': [],
    'fileName': 'test-file-name',
    'shouldExpandObjects': true,
    'endOfLineValue': '\n',
    'delimiter': ',',
    'quote': '"',
    'booleanValues': {'true':'Yes', 'false':'No'},
});

• Options


keys

Keys for first row of csv. Set the keys in an array of objects according to the format below. Using the key/as format allows for you to set the key in the data object and display the as within the final csv as a proper title for example.

If empty, the keys in the first object of the array will be used as column names.

  • Type: Array
  • Default: []
  • Format: [ {key: '', as: ''}, ... ]

Usage Example:

let keys = [
    {
        key: 'make',
        as: 'Make',
    }
];

//Set keys in 3 different ways
let otc = new ObjectToCSV({ keys });
// otc.setKeys(keys);
// otc.keys = keys;

//Get
keys = otc.keys;

data

The data that fills the csv

  • Type: Array
  • Default: []
  • Format: [ {...}, ... ]

Usage Example:

let data = [
    { 
      'make': 'Ford',
      'model': 'Mustang',
      'new': true
    },
];

//Set data in 3 different ways
let otc = new ObjectToCSV({ data });
// otc.setData(data);
// otc.data = data;

//Get
data = otc.data;

fileName

The file name for downloading the csv.

  • Type: String
  • Default: file

Usage Example:

let fileName = 'file-name';

//Set file name in 3 different ways
let otc = new ObjectToCSV({ fileName });
// otc.setFileName(fileName);
// otc.fileName = fileName;

//Get
fileName = otc.fileName;

shouldExpandObjects

Should flatten nested objects. This is a boolean to check if JSON.stringify() should be used on arrays and objects within the data.

  • Type: Boolean
  • Default: false

Usage Example:

let shouldExpandObjects = false;

//Set shouldExpandObjects in 3 different ways
let otc = new ObjectToCSV({ shouldExpandObjects });
// otc.setShouldExpandObjects(shouldExpandObjects);
// otc.shouldExpandObjects = shouldExpandObjects;

//Get
shouldExpandObjects = otc.shouldExpandObjects;

endOfLineValue

Specify an end of line value for separating rows other than the default line ending.

  • Type: String
  • Default: \n

Usage Example:

let endOfLineValue = '\n';

//Set endOfLineValue in 3 different ways
let otc = new ObjectToCSV({ endOfLineValue });
// otc.setEndOfLineValue(endOfLineValue);
// otc.endOfLineValue = endOfLineValue;

//Get
endOfLineValue = otc.endOfLineValue;

delimiter

CSV delimiter of columns

  • Type: String
  • Default: ,

Usage Example:

let delimiter = ',';

//Set delimiter in 3 different ways
let otc = new ObjectToCSV({ delimiter });
// otc.setDelimiter(delimiter);
// otc.delimiter = delimiter;

//Get
delimiter = otc.delimiter;

quote

The quote around cell values and column names.

  • Type: String
  • Default: "

Usage Example:

let quote = '"';

//Set quote in 3 different ways
let otc = new ObjectToCSV({ quote });
// otc.setQuote(quote);
// otc.quote = quote;

//Get
quote = otc.quote;

booleanValues

The values to show if a boolean value is present in the data for the csv.

  • Type: Object
  • Default: { 'true': 'TRUE', 'false': 'FALSE' }
  • Format: { 'true': 'Yes', 'false': 'No' }

Usage Example:

let booleanValues = { 'true': 'Yes', 'false': 'No'  };

//Set quote in 3 different ways
let otc = new ObjectToCSV({ booleanValues });
// otc.setBooleanValues(booleanValues);
// otc.booleanValues = booleanValues;

//Get
booleanValues = otc.booleanValues;

• Commands


getCSV()

Get CSV as a string from given attributes

  • Returns: String

Usage Example:

let otc = new ObjectToCSV();
let csv = otc.getCSV();

getResponseHeaders()

Get response headers for sending a CSV download to the client

  • Returns: Object
  • Format: {'Content-Disposition': '...', 'Content-Type': '...'}

Usage Example:

let otc = new ObjectToCSV();
let responseHeaders = otc.getResponseHeaders();
let csv = otc.getCSV();

//Example
//1. Set up your server
//In this case, we're just going to use the http module
const http = require('http');

//2. Create server
http.createServer((req, res) => {
    const url = req.url;

    //3. Set up a route on your sever to download a test csv
    if (url == '/download') {
        res.setHeader('Content-Type', responseHeaders['Content-Type']);
        res.setHeader('Content-Disposition', responseHeaders['Content-Disposition']);
        res.write(csv, 'text/csv');
        res.end();
    }
}).listen(8080);

• Say Hi

Tweet at me: @markmiscavage.

• License

MIT License

Copyright (c) 2020 Mark Miscavage

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.