|
1 | | -import { checkSpecialCharsAndEmpty } from '../helpers/check-special-chars-and-empty'; |
| 1 | +import { appendElement } from '../helpers/append-element'; |
2 | 2 |
|
3 | 3 | export const convertArrayOfObjectsToCSV = (data, { header, separator }) => { |
4 | 4 | const array = [...data]; |
5 | 5 | let csv = ''; |
6 | 6 |
|
7 | 7 | if (header) { |
8 | 8 | header.forEach((headerEl, i) => { |
9 | | - const includesSpecials = checkSpecialCharsAndEmpty(headerEl); |
10 | | - csv |
11 | | - += (includesSpecials ? `"${headerEl}"` : headerEl) |
12 | | - + (Object.keys(header).length - 1 === i ? '' : separator) |
13 | | - + (Object.keys(header).length - 1 === i ? '\n' : ''); |
| 9 | + const thisHeaderEl = headerEl || ''; |
| 10 | + |
| 11 | + csv += appendElement(thisHeaderEl, header.length, i, separator); |
14 | 12 | }); |
15 | 13 | } |
16 | 14 |
|
17 | 15 | array.forEach((row, idx) => { |
| 16 | + const thisRow = Object.keys(row); |
18 | 17 | if (!header && idx === 0) { |
19 | | - Object.keys(row).forEach((key, i) => { |
| 18 | + thisRow.forEach((key, i) => { |
20 | 19 | const value = key || ''; |
21 | | - const includesSpecials = checkSpecialCharsAndEmpty(value); |
22 | 20 |
|
23 | | - csv |
24 | | - += (includesSpecials ? `"${value}"` : value) |
25 | | - + (Object.keys(row).length - 1 === i ? '' : separator) |
26 | | - + (Object.keys(row).length - 1 === i ? '\n' : ''); |
| 21 | + csv += appendElement(value, thisRow.length, i, separator); |
27 | 22 | }); |
28 | 23 | } |
29 | | - Object.keys(row).forEach((key, i) => { |
| 24 | + |
| 25 | + thisRow.forEach((key, i) => { |
30 | 26 | const value = row[key] || ''; |
31 | | - const includesSpecials = checkSpecialCharsAndEmpty(value); |
32 | 27 |
|
33 | | - csv |
34 | | - += (includesSpecials ? `"${value}"` : value) |
35 | | - + (Object.keys(row).length - 1 === i ? '' : separator) |
36 | | - + (Object.keys(row).length - 1 === i ? '\n' : ''); |
| 28 | + csv += appendElement(value, thisRow.length, i, separator); |
37 | 29 | }); |
38 | 30 | }); |
39 | 31 |
|
|
0 commit comments