I have and error while converting CSV to Array

104 views Asked by At

Is there any way of fixing this CSV error after I convert a CSV to an array? Console log the objects in the array, the last property has an error

Code

const csvFileToArray = (string, delimiter = ",") => {
    const csvHeader = string
        .slice(0, string.indexOf("\n"))
        .split(delimiter);
    const csvRows = string.slice(string.indexOf("\n") + 1).split("\n");

    const array = csvRows.map((row) => {
        const values = row.split(delimiter);
        const obj = csvHeader.reduce((object, header, index) => {
            object[header] = values[index];
            return object;
        }, {});
        console.log(obj)
        return obj;
    });
    localStorage.setItem("bulkUpload", JSON.stringify(array));
    handleClose();
    return setArray(array);
};

Output

{
    "category": "5f1a2779-f4b7-4e0d-a8fd-d2fff7e04418",
    "name": "product",
    "bulk_image": "image_url",
    "quantity": "18",
    "currency": "USD",
    "vendor": "815c5741-ed74-454f-85cd-c8f0a1aeee64",
    "price\r": "1399\r"
}
1

There are 1 answers

0
Savin Osuka On

Phuzi's solution worked. Terminating with a single \n was the issue. It should be terminated with \r\n.

Here is the correct code

const csvHeader = string
        .slice(0, string.indexOf("\r\n"))
        .split(delimiter);
    const csvRows = string.slice(string.indexOf("\r\n") + 1).split("\r\n");