csv-to-js-parser
Advanced tools
Comparing version 2.1.4 to 2.2.0
47
app.js
@@ -26,4 +26,42 @@ /* | ||
'use strict'; | ||
module.exports.csvToObj = function(data, delimeter, description, isSorted) | ||
module.exports.csvToObj = function(data, param1, param2) | ||
{ | ||
if (typeof data !== 'string' || | ||
(typeof param1 === 'object' && typeof param2 === 'object') || | ||
(typeof param1 === 'string' && typeof param2 === 'string') || | ||
(param1 && (typeof param1 !== 'object' && typeof param1 !== 'string')) || | ||
(param2 && (typeof param2 !== 'object' && typeof param2 !== 'string'))) | ||
throw new Error('Incorrect parameters'); | ||
let description; | ||
let delimeter; | ||
if (param1 || param2) | ||
{ | ||
if (param1) | ||
{ | ||
if (typeof param1 === 'string') | ||
{ | ||
delimeter = param1; | ||
} | ||
else | ||
{ | ||
description = param1; | ||
} | ||
} | ||
if (param2) | ||
{ | ||
if (typeof param2 === 'string') | ||
{ | ||
delimeter = param2; | ||
} | ||
else | ||
{ | ||
description = param2; | ||
} | ||
} | ||
} | ||
if (!delimeter) delimeter = ','; | ||
//Spliting data by rows | ||
@@ -62,2 +100,8 @@ { | ||
} | ||
/* | ||
console.log(delimeter); | ||
console.log(description); | ||
*/ | ||
//Deleting header from data | ||
@@ -264,2 +308,3 @@ data.shift(); | ||
if (!obj[0]) throw new Error('Object error'); | ||
if (!delimeter) delimeter = ','; | ||
if (!rowDelimeter) | ||
@@ -266,0 +311,0 @@ { |
@@ -13,9 +13,9 @@ 'use strict'; | ||
{ | ||
customer_id: {type: 'number', order: 1}, | ||
customer_id: {type: 'number', group: 1}, | ||
product: {type: 'string'}, | ||
product_id: {type: 'number'}, | ||
customer_name: {type: 'string', order: 2}, | ||
customer_name: {type: 'string', group: 2}, | ||
price: {type: 'number'}, | ||
closed: {type: 'boolean'}, | ||
customer_status: {type: 'number', order: 2} | ||
customer_status: {type: 'number', group: 2} | ||
}; | ||
@@ -22,0 +22,0 @@ |
{ | ||
"name": "csv-to-js-parser", | ||
"version": "2.1.4", | ||
"version": "2.2.0", | ||
"description": "Converting csv data into array of JavaScript objects. This module can group input data.", | ||
@@ -20,4 +20,4 @@ "main": "app.js", | ||
"devDependencies": { | ||
"mocha": "^7.1.1" | ||
"mocha": "^8.0.1" | ||
} | ||
} |
@@ -89,4 +89,4 @@ # Преобразование данных csv в объекты JavaScript | ||
* data: csv таблица в виде строки. | ||
* delimeter: разделитель столбцов во входной таблице. | ||
* description [optional]: описание входной таблицы. | ||
* delimeter [опционально]: разделитель столбцов во входной таблице. Если не задан, то по умолчанию используется запятая ",". | ||
* description [опционально]: описание входной таблицы. | ||
@@ -100,2 +100,4 @@ В параметре description описывается входная таблица: | ||
Параметры delimeter и description можно задавать в другом порядке: сначала description, затем delimeter . | ||
Рассмотрим другой пример, где можно лучше увидеть как работает группировка. Пусть в качестве входных данных выступает таблица 2. | ||
@@ -190,3 +192,3 @@ | ||
* arrayKeys: имена свойств во входном объекте, которые являются массивами. | ||
* newArrayKeys [optional]: если задан, то имена свойств, которые переопределят свойства из arrayKeys, то есть в выходном объекте вместо свойств arrayKeys будут свойства newArrayKeys. | ||
* newArrayKeys [опционально]: если задан, то имена свойств, которые переопределят свойства из arrayKeys, то есть в выходном объекте вместо свойств arrayKeys будут свойства newArrayKeys. | ||
@@ -293,3 +295,3 @@ Результат работы функции combineArrays для примера из таблицы 1 представлен ниже: | ||
* arrayKeys: имена свойств во входном объекте, которые нужно сделать отдельными массивами . | ||
* newArrayKeys [optional]: если задан, то имена свойств, которые переопределят свойства из arrayKeys, то есть в выходном объекте вместо свойств arrayKeys будут свойства newArrayKeys. | ||
* newArrayKeys [опционально]: если задан, то имена свойств, которые переопределят свойства из arrayKeys, то есть в выходном объекте вместо свойств arrayKeys будут свойства newArrayKeys. | ||
@@ -319,6 +321,6 @@ Результатом работы этой функции будет первоначальный объект, полученный из csvToObj. | ||
* obj: входной массив объектов (формат должен соответствовать тому, который возвращает csvToObj). | ||
* delimeter: разделитель столбцов в выходной таблице. | ||
* rowDelimeter [optional]: разделитель строк. Если не задан, то по умолчанию используется "LF" (\n). Для windows разумно указывать в этом параметре разделитель "CRLF" (\r\n). | ||
* delimeter [опционально]: разделитель столбцов в выходной таблице. Если не задан, то по умолчанию используется запятая ",". | ||
* rowDelimeter [опционально]: разделитель строк. Если не задан, то по умолчанию используется "LF" (\n). Для windows разумно указывать в этом параметре разделитель "CRLF" (\r\n). | ||
## Лицензия MIT | ||
https://github.com/Mendeo/csv-to-js-parser/blob/master/LICENSE |
@@ -90,3 +90,5 @@ # Convert csv data to an array of JavaScript objects | ||
* data: csv table as a string. | ||
* delimeter: column separator in the input table. | ||
* delimeter [optional]: column separator in the input table. If not specified, then the default is comma ",". | ||
* description [optional]: description of the input table. | ||
@@ -100,2 +102,4 @@ | ||
The delimeter and description parameters can be set in a different order: first description, then delimeter. | ||
Consider another example where you can better see how grouping works. Let the input data be table 2. | ||
@@ -318,3 +322,3 @@ | ||
* obj: input array of objectc (the format must match the one returned by csvToObj). | ||
* delimeter: column delimiter in the output table. | ||
* delimeter [optional]: column delimiter in the output table. If not specified, then the default is comma ",". | ||
* rowDelimeter [optional]: rows separator. If not specified, then the default is "LF" (\n). For windows, it is reasonable to specify the "CRLF" delimiter (\r\n). | ||
@@ -321,0 +325,0 @@ |
@@ -725,5 +725,12 @@ 'use strict'; | ||
{ | ||
const result = app.csvToObj(csv, ';', description); | ||
let msg = whereNotEqual(expected, result); | ||
if (msg) throw new Error(msg); | ||
const result1 = app.csvToObj(csv, ';', description); | ||
const result2 = app.csvToObj(csv, description, ';'); | ||
const result3 = app.csvToObj(csv.replace(/;/g, ','), description); | ||
let msg; | ||
msg = whereNotEqual(expected, result1); | ||
if (msg) throw new Error(msg) + ' explicit params one order'; | ||
msg = whereNotEqual(expected, result2); | ||
if (msg) throw new Error(msg) + ' explicit params other order'; | ||
msg = whereNotEqual(expected, result3); | ||
if (msg) throw new Error(msg) + ' implicit delimeter'; | ||
} | ||
@@ -758,5 +765,10 @@ it ('should return normal object', () => doTest(normal_csv, normal_obj, normal_description)); | ||
const result = app.objToCsv(obj, ';'); | ||
const result1 = app.objToCsv(obj, ';'); | ||
const result2 = app.objToCsv(obj); | ||
//fs.writeFileSync('expected.csv', expected); | ||
//fs.writeFileSync('result.csv', result); | ||
if (result !== expected) throw new Error(`Expected:\n${expected}\n\nBut got:\n${result}`); | ||
if (result1 !== expected) throw new Error(`Expected (explicit delimeter):\n${expected}\n\nBut got:\n${result}`); | ||
let commaExpected = expected.replace(/;/g, ','); | ||
if (result2 !== commaExpected) throw new Error(`Expected (implicit delimeter):\n${commaExpected}\n\nBut got:\n${result}`); | ||
} | ||
@@ -763,0 +775,0 @@ it('should return normal_csv', () => doTest(normal_obj, normal_csv)); |
57158
1267
324