diff --git a/papaparse.js b/papaparse.js index 255d2ea..c3e3e56 100644 --- a/papaparse.js +++ b/papaparse.js @@ -193,7 +193,7 @@ function CsvToJson(_input, _config) { _config = _config || {}; - _config.dynamicTyping = _config.dynamicTyping || false; + _config.dynamicTyping = new DynamicTypingConfig(_config.dynamicTyping); if (_config.worker && Papa.WORKERS_SUPPORTED) { @@ -415,6 +415,24 @@ } } + function DynamicTypingConfig(config) + { + this._config = config; + } + DynamicTypingConfig.prototype.constructor = DynamicTypingConfig; + DynamicTypingConfig.prototype.isIncluded = function(field) + { + if (typeof this._config === 'function') + { + return this._config(field) === true; + } + if (typeof this._config === 'object') + { + return this._config[field] === true; + } + return !!this._config; + }; + /** ChunkStreamer is the base prototype for various streamer implementations. */ function ChunkStreamer(config) { @@ -969,7 +987,7 @@ function parseDynamic(field, value) { - if ((_config.dynamicTyping[field] || _config.dynamicTyping) === true) + if (_config.dynamicTyping.isIncluded(field)) { if (value === 'true' || value === 'TRUE') return true; diff --git a/tests/test-cases.js b/tests/test-cases.js index 81f3d53..f9e93ea 100644 --- a/tests/test-cases.js +++ b/tests/test-cases.js @@ -693,6 +693,24 @@ var PARSE_TESTS = [ }] } }, + { + description: "Dynamic typing by indices can be determined by function", + input: '001,002,003', + config: { dynamicTyping: function(field) { return (field % 2) === 0; } }, + expected: { + data: [[1, "002", 3]], + errors: [] + } + }, + { + description: "Dynamic typing by headers can be determined by function", + input: 'A_as_int,B,C_as_int\r\n001,002,003', + config: { header: true, dynamicTyping: function(field) { return /_as_int$/.test(field); } }, + expected: { + data: [{"A_as_int": 1, "B": "002", "C_as_int": 3}], + errors: [] + } + }, { description: "Blank line at beginning", input: '\r\na,b,c\r\nd,e,f',