UNPKG

1.29 kBJavaScriptView Raw
1function CSVObject(data, feed) {
2 if (this.isLast()) {
3 return feed.close();
4 }
5
6 if (!this.columns) {
7 this.columns = data.map(name => name.replace(/\./g, ''));
8
9 const countCols = {};
10 const renamedCols = {};
11 this.columns.forEach((colname) => {
12 countCols[colname] = (!countCols[colname]) ? 1 : (countCols[colname] + 1);
13 });
14 this.columns = this.columns.map((colname) => {
15 if (countCols[colname] > 1) {
16 renamedCols[colname] = (!renamedCols[colname]) ? 1 : (renamedCols[colname] + 1);
17 return colname + renamedCols[colname];
18 }
19 return colname;
20 });
21 return feed.end();
22 }
23
24 if (Array.isArray(data)) {
25 const obj = {};
26 data.forEach((item, index) => {
27 const columnName = this.columns[index] ? this.columns[index].trim() : 'Column #'.concat(index);
28 obj[columnName] = item;
29 });
30 return feed.send(obj);
31 }
32
33 feed.end();
34}
35
36/**
37 * Take `Array` and transform rows into object.
38 * Each row (Array) is tranformed
39 * into a object where keys are the value of the first row
40 *
41 * @name CSVObject
42 * @param {undefined} none
43 * @returns {Object}
44 */
45export default {
46 CSVObject,
47};