19 lines
585 B
TypeScript
19 lines
585 B
TypeScript
import { Injectable } from '@angular/core';
|
|
|
|
import { ToCsvType } from './to-csv-type';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class ToCsvService {
|
|
toCsv(headers: Record<string, string>, data: unknown[]): string {
|
|
const header = Object.keys(headers);
|
|
const replacer = (key: string, value: string | number | null) => (value === null ? '' : value);
|
|
const csv = data.map((row) =>
|
|
header.map((fieldName) => JSON.stringify((row as ToCsvType)[headers[fieldName]], replacer)).join(','),
|
|
);
|
|
csv.unshift(header.join(','));
|
|
return csv.join('\r\n');
|
|
}
|
|
}
|