Files
windmill/frontend/src/lib/components/table/tableUtils.ts
T

59 lines
1.4 KiB
TypeScript

import { Parser } from '@json2csv/plainjs'
export function isLink(value: string) {
return value?.startsWith('http://') || value?.startsWith('https://')
}
export function isEmail(value: string) {
return value?.includes('@')
}
export function computeStructuredObjectsAndHeaders(
objects: Array<Record<string, any>>,
headerOrder?: string[]
): [
string[],
{
_id: number
rowData: Record<string, any>
}[]
] {
if (Array.isArray(objects)) {
let nextId = 1
// Seed headers from the explicit order when provided. Object key order
// can't be trusted here: integer-like keys (e.g. "1234") are enumerated
// first in ascending numeric order regardless of insertion order.
let hds: string[] = headerOrder ? [...headerOrder] : []
let objs = objects.map((obj) => {
let rowData = obj && typeof obj == 'object' ? obj : {}
if (Array.isArray(rowData)) {
rowData = Object.fromEntries(rowData.map((x, i) => ['col' + i, x]))
}
let ks = Object.keys(rowData)
ks.forEach((x) => {
if (!hds.includes(x)) {
hds.push(x)
}
})
return {
_id: nextId++,
rowData
}
})
return [hds, objs]
} else {
return [[], []]
}
}
export function convertJsonToCsv(arr: Array<Record<string, any>>): string {
try {
const parser = new Parser({})
const csv = parser.parse(arr)
return csv
} catch (err) {
throw new Error('An error occurred when generating CSV:' + err)
}
}