-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsvParser.js
More file actions
51 lines (47 loc) · 1.1 KB
/
csvParser.js
File metadata and controls
51 lines (47 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// csvParser.js
function parseCSVLine(line) {
const fields = [];
let cur = '';
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (ch === '"') {
if (inQuotes && i + 1 < line.length && line[i + 1] === '"') {
cur += '"';
i++;
} else {
inQuotes = !inQuotes;
}
} else if (ch === ',' && !inQuotes) {
fields.push(cur.trim());
cur = '';
} else {
cur += ch;
}
}
fields.push(cur.trim());
return fields;
}
function setNested(obj, path, value) {
const keys = path.split('.');
let cur = obj;
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
if (i === keys.length - 1) {
cur[k] = value;
} else {
if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {};
cur = cur[k];
}
}
}
function buildObjectFromRow(headers, rowValues) {
const obj = {};
for (let i = 0; i < headers.length; i++) {
const header = headers[i];
const val = rowValues[i] ?? '';
setNested(obj, header, val);
}
return obj;
}
module.exports = { parseCSVLine, buildObjectFromRow };