1
0
Fork 0
mirror of synced 2024-07-30 02:26:11 +12:00

Return null instead of undefined

This commit is contained in:
Adria Navarro 2023-05-02 12:46:53 +01:00
parent 650cbc1f01
commit 6e7c78362e
2 changed files with 15 additions and 12 deletions

View file

@ -1,19 +1,22 @@
import csv from "csvtojson"
export async function jsonFromCsvString(csvString: string) {
const castedWithEmptyStrings = await csv().fromString(csvString)
if (!castedWithEmptyStrings.length) {
return []
}
const castedWithEmptyValues = await csv({ ignoreEmpty: true }).fromString(
csvString
)
// By default the csvtojson library casts empty values as empty strings. This is causing issues on conversion.
// ignoreEmpty will remove the key completly if empty, so creating this empty object will ensure we return the values with the keys but empty values
const emptyObject = Object.keys(castedWithEmptyStrings[0]).reduce(
(p, v) => ({ ...p, [v]: undefined }),
{}
)
const result = await csv({ ignoreEmpty: false }).fromString(csvString)
result.forEach((r, i) => {
for (const [key] of Object.entries(r).filter(
([key, value]) => value === ""
)) {
if (castedWithEmptyValues[i][key] === undefined) {
r[key] = null
}
}
})
let result = await csv({ ignoreEmpty: true }).fromString(csvString)
result = result.map(r => ({ ...emptyObject, ...r }))
return result
}

View file

@ -21,9 +21,9 @@ describe("csv", () => {
const result = await jsonFromCsvString(csvString)
expect(result).toEqual([
{ id: "1", optional: undefined, title: "aaa" },
{ id: "1", optional: null, title: "aaa" },
{ id: "2", optional: "value", title: "bbb" },
{ id: "3", optional: undefined, title: "ccc" },
{ id: "3", optional: null, title: "ccc" },
])
result.forEach(r =>
expect(Object.keys(r)).toEqual(["id", "optional", "title"])