Skip to content

Commit

Permalink
fix: Process header cells as any other cell (#244)
Browse files Browse the repository at this point in the history
  • Loading branch information
juanjoDiaz authored and knownasilya committed Feb 2, 2018
1 parent efe9888 commit 1fcde13
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
40 changes: 29 additions & 11 deletions lib/JSON2CSVBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,8 @@ class JSON2CSVBase {
(typeof field === 'string')
? field
: (field.label || field.value)
).map(header =>
JSON.stringify(header)
.replace(/"/g, this.params.quote)
)
.map(header => this.processValue(header, true))
.join(this.params.delimiter);
}

Expand Down Expand Up @@ -86,7 +84,7 @@ class JSON2CSVBase {
}

return this.params.fields
.map(fieldInfo => this.processField(row, fieldInfo))
.map(fieldInfo => this.processCell(row, fieldInfo))
.join(this.params.delimiter);
}

Expand All @@ -97,14 +95,25 @@ class JSON2CSVBase {
* @param {Object} fieldInfo Details of the field to process to be a CSV cell
* @returns {String} CSV string (cell)
*/
processField(row, fieldInfo) {
const isFieldInfoObject = typeof fieldInfo === 'object';
const defaultValue = isFieldInfoObject && 'default' in fieldInfo
? fieldInfo.default
: this.params.defaultValue;
const stringify = isFieldInfoObject && fieldInfo.stringify !== undefined
processCell(row, fieldInfo) {
const stringify = typeof fieldInfo === 'object' && fieldInfo.stringify !== undefined
? fieldInfo.stringify
: true;

return this.processValue(this.getValue(row, fieldInfo), stringify);
}

/**
* Create the content of a specfic CSV row cell
*
* @param {Object} row JSON object representing the CSV row that the cell belongs to
* @param {Object} fieldInfo Details of the field to process to be a CSV cell
* @returns {Any} Field value
*/
getValue(row, fieldInfo) {
const defaultValue = typeof fieldInfo === 'object' && 'default' in fieldInfo
? fieldInfo.default
: this.params.defaultValue;

let value;
if (fieldInfo) {
Expand All @@ -123,10 +132,19 @@ class JSON2CSVBase {
}
}

value = (value === null || value === undefined)
return (value === null || value === undefined)
? defaultValue
: value;
}

/**
* Create the content of a specfic CSV row cell
*
* @param {Any} value Value to be included in a CSV cell
* @param {Boolean} stringify Details of the field to process to be a CSV cell
* @returns {String} Value stringified and processed
*/
processValue(value, stringify) {
if (value === null || value === undefined) {
return undefined;
}
Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/csv/excelStrings.csv
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"carModel","price","color"
"=""carModel""","=""price""","=""color"""
"=""Audi""",0,"=""blue"""
"=""BMW""",15000,"=""red"""
"=""Mercedes""",20000,"=""yellow"""
Expand Down

0 comments on commit 1fcde13

Please sign in to comment.