Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guarantee column order of objects. With headers. #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 17 additions & 35 deletions lib/csv-express.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ exports.ignoreNullOrUndefined = true;
*/

function escape(field) {
if (exports.ignoreNullOrUndefined && field == undefined) {
if (exports.ignoreNullOrUndefined && field === undefined) {
return '';
}
if (exports.preventCast) {
Expand All @@ -38,27 +38,6 @@ function escape(field) {
return '"' + String(field).replace(/\"/g, '""') + '"';
}

/**
* Convert an object to an array of property values.
*
* Example:
* objToArray({ name: "john", id: 1 })
* // => [ "john", 1 ]
*
* @param {Object} obj The object to convert.
* @return {Array} The array of object properties.
* @api private
*/

function objToArray(obj) {
var result = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
result.push(obj[prop]);
}
}
return result;
}


/*
Expand All @@ -75,23 +54,26 @@ res.csv = function(data, csvHeaders, headers, status) {

this.charset = this.charset || 'utf-8';
this.header('Content-Type', 'text/csv');

if (csvHeaders) {
var header = [];
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
header.push(prop);
}
}
body += header + '\r\n';
}

var csvHeader_arr = [], csvHeader_pos = {}; //twice for better access of position

data.forEach(function(item) {
if (!(item instanceof Array)) {
item = objToArray(item);
var arr = [];
if (item instanceof Array) arr = item;
else
for (var prop in item) { //former objToArray but with correct header_csv position
if (item.hasOwnProperty(prop)) {
if (csvHeader_pos[prop] === undefined) {
csvHeader_pos[prop] = csvHeader_arr.length;
csvHeader_arr.push(prop);
}
arr[csvHeader_pos[prop]] = item[prop];
}
}
body += item.map(escape).join(exports.separator) + '\r\n';
body += arr.map(escape).join(exports.separator) + '\r\n';
});

if (csvHeaders && csvHeader_arr.length) body = csvHeader_arr.map(escape).join(exports.separator) + '\r\n' + body;

if (this.charset !== 'utf-8') {
body = iconv.encode(body, this.charset);
Expand Down