-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVToJSON.ts
32 lines (31 loc) · 1.01 KB
/
CSVToJSON.ts
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
/**
* Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.
* @param data - The CSV string.
* @param delimiter - The delimiter used in the CSV string.
* @returns A 2D array of objects.
* @example
* ```
* CSVToJSON('col1,col2\na,b\nc,d');
* // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
* CSVToJSON('col1;col2\na;b\nc;d', ';');
* // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
* ```
* @category String
* @public
* @since 0.1.15
*/
const CSVToJSON = (data: string, delimiter = ",") => {
const titles = data.slice(0, data.indexOf("\n")).split(delimiter);
return data
.slice(data.indexOf("\n") + 1)
.split("\n")
.map((v) => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => {
// eslint-disable-next-line no-param-reassign
obj[title] = values[index];
return obj;
}, {} as { [key: string]: string });
});
};
export default CSVToJSON;