Return null instead of undefined
This commit is contained in:
parent
650cbc1f01
commit
6e7c78362e
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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"])
|
||||
|
|
Loading…
Reference in New Issue