1
0
Fork 0
mirror of synced 2024-09-08 21:51:58 +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" import csv from "csvtojson"
export async function jsonFromCsvString(csvString: string) { export async function jsonFromCsvString(csvString: string) {
const castedWithEmptyStrings = await csv().fromString(csvString) const castedWithEmptyValues = await csv({ ignoreEmpty: true }).fromString(
if (!castedWithEmptyStrings.length) { csvString
return [] )
}
// By default the csvtojson library casts empty values as empty strings. This is causing issues on conversion. // 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 // 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( const result = await csv({ ignoreEmpty: false }).fromString(csvString)
(p, v) => ({ ...p, [v]: undefined }), 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 return result
} }

View file

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