From 1fcde1334388e91185767cd96c88b9ac14e358bb Mon Sep 17 00:00:00 2001 From: Juanjo Diaz Date: Fri, 2 Feb 2018 14:20:04 -0800 Subject: [PATCH] fix: Process header cells as any other cell (#244) --- lib/JSON2CSVBase.js | 40 ++++++++++++++++++++++-------- test/fixtures/csv/excelStrings.csv | 2 +- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/lib/JSON2CSVBase.js b/lib/JSON2CSVBase.js index 6c681841..43f8469d 100644 --- a/lib/JSON2CSVBase.js +++ b/lib/JSON2CSVBase.js @@ -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); } @@ -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); } @@ -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) { @@ -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; } diff --git a/test/fixtures/csv/excelStrings.csv b/test/fixtures/csv/excelStrings.csv index 2d0e1acd..6738a26a 100644 --- a/test/fixtures/csv/excelStrings.csv +++ b/test/fixtures/csv/excelStrings.csv @@ -1,4 +1,4 @@ -"carModel","price","color" +"=""carModel""","=""price""","=""color""" "=""Audi""",0,"=""blue""" "=""BMW""",15000,"=""red""" "=""Mercedes""",20000,"=""yellow"""