Added fromCsv
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 1m43s

This commit is contained in:
2024-11-09 16:30:05 -05:00
parent 0eab2630ad
commit 341ef37205
4 changed files with 30 additions and 8 deletions

View File

@ -1,5 +1,22 @@
import {ASet} from './aset.ts';
import {dotNotation, flattenObj, JSONAttemptParse, JSONSanitize} from './objects.ts';
import {dotNotation, flattenObj, JSONSanitize} from './objects.ts';
export function fromCsv<T = any>(csv: string, hasHeaders=true): T[] {
const row = csv.split('\n');
let headers: any = hasHeaders ? row.splice(0, 1)[0] : null;
if(headers) headers = headers.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g);
return <T[]>row.map(r => {
const props: string[] = <any>r.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g);
const h = headers || (Array(props.length).fill(null).map((r, i) => {
let letter = '';
const first = i / 26;
if(first > 1) letter +=
i % 26
i
}));
return h.reduce((acc: any, h: any, i: number) => ({...acc, [h]: props[i]}), {})
})
}
/**
* Convert an object to a CSV string