3

I have a function that converts an array to a csv file. It separates on commas but when there is a comma in one of the values of the array, it separates there as well. I've tried to wrap the comma in quotes and to escape it but it still breaks the csv. Any ideas on how to separate on comma but not from within the value of the array?

convertArrayOfObjectsToCSV: function(args) {
            var result, ctr, keys, columnDelimiter, lineDelimiter, data;

            data = args.data || null;
            if (data == null || !data.length) {
                return null;
            }

            columnDelimiter = args.columnDelimiter || ',';
            lineDelimiter = args.lineDelimiter || '\n';

            keys = Object.keys(data[0]);

            result = '';
            result += keys.join(columnDelimiter);
            result += lineDelimiter;

            data.forEach(function(item) {
                ctr = 0;
                keys.forEach(function(key) {
                    if (ctr > 0) result += columnDelimiter;

                    result += item[key];
                    ctr++;
                });
                result += lineDelimiter;
            });

            return result;
        },
        downloadCSV: function(args) {
            var data, filename, link, csvArray;

            csvArray = ids.map(function(id) {
                return {
                    'id': id.id,
                    'image': id.image,
                    'desc': id.desc
                };
            });
            var csv = utilities.convertArrayOfObjectsToCSV({
                data: csvArray
            });


            if (csv == null) return;

            filename = args.filename || 'export.csv';

            if (!csv.match(/^data:text\/csv/i)) {
                csv = 'data:text/csv;charset=utf-8,' + csv;
            }
            data = encodeURI(csv);

            link = document.createElement('a');
            link.setAttribute('href', data);
            link.setAttribute('download', filename);
            link.click();
        }
    };

Here is a sample of the data created as csvArray:

[{id:123,
image:image,
desc : "hello here is a comma , I am after the comma"}]
1
  • quote your text values with double quotes Commented Jul 10, 2017 at 15:53

1 Answer 1

1

change how you write text to result as below

data.forEach(function(item) {
    ctr = 0;
    keys.forEach(function(key) {
        if (ctr > 0) result += columnDelimiter;
        result += "\"" + item[key].replace(/"/g, '\\"') + "\"";
        ctr++;
    });
    result += lineDelimiter;
});

Just adding text in between quotes may solve this issue.

Sign up to request clarification or add additional context in comments.

1 Comment

Should escape internal double quotes also ... in case they exist