Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here.

For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from affecting other data in adjacent cells.

var newS = {
    Name: "https://www.someweb.com/product/2019-new-shoulder-bags-leather-bucket-bag/452346283.html?d1_posid=6c776030d97bebe241c60070a53e7683&dspm=pcen.hp.relatedviewed.3.qJcEmZmc4A8ZV2ksdlct&resource_id=452346283#hp1507_reit-3-5|null:2001:r1045009996.json",
    rating: "Google Inc",
    rating: "Google Inc",
    Price: "554.52"
}
stockData.push(newS);
}

function convertArrayOfObjectsToCSV(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;
}

Answer №1

The concern lies not in the displayed portion, but rather in the downloadCSV function within your fiddle.

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

encodeURI is typically not the best option for properly encoding data in a URL context.

In this case, it should use encodeURIComponent instead. However, since this would also encode characters within data:text/csv;charset=utf-8,, these two steps need to be reversed:

csv = encodeURIComponent(csv)
csv = 'data:text/csv;charset=utf-8,' + csv;
data = csv; // keep this so that the rest of your code can still function correctly with the data variable

https://jsfiddle.net/vky7b5dg/

I have removed the if condition here - if the data already started with data:text/csv, it would not work anyway. Thus, it must be removed prior to URL encoding and added back afterwards. While this function aims to be very generic, it seems unnecessary for your specific use case.


(This still lacks proper escaping for CSV data. If any of your data fields contain a ,, it may cause issues. However, addressing this concern falls on the convertArrayOfObjectsToCSV function, not the download functionality described here.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to bypass a transition using JavaScript

Hello everyone, I would like to start by apologizing for any mistakes in my English. I have been working on a website, which is currently available here: As you scroll down, the height of the image below the menu decreases. I am trying to make the navig ...

Click on the React JS infinite render component to load more items

Just diving into the world of react/next and I'm a bit stuck on this issue. I've searched high and low, tried different solutions, but I can't seem to figure out what I'm missing or not grasping here. I understand that loadStats() is ...

Where is the best place for the heavy lifting in Redux - reducer, action, container, or presentation component?

I've been exploring the concept of container/presentational component separation as explained in this article. However, I find myself a bit confused about where certain parts of my code should be placed. Consider a simple list of items. When an item ...

React Array Not Behaving Properly When Checkbox Unchecked and Item Removed

When using my React Table, I encountered an issue with checkboxes. Each time I check a box, I aim to add the corresponding Id to an empty array and remove it when unchecked. However, the current implementation is not functioning as expected. On the first c ...

A guide on transforming HTML into a variable using JavaScript

Having trouble converting HTML to a JavaScript variable. This is my HTML code: <div onclick="openfullanswer('2','Discription part','This is the code part');"> I want to create this HTML code dynamically, but I&apo ...

In my Angular application, I have two div elements that I want to toggle between. When a button located in the first div is clicked, I need

I am working on a code snippet that requires me to hide div1 and display div2 when the button in div1 is clicked using Angular HTML5. Currently, I have two separate modal pop up template files and JS controllers for each of them. Instead of having two po ...

Using Mocha with the --watch flag enabled causes issues with ES6 modules and results in error messages

I've been attempting to configure Mocha to automatically monitor for changes in my files using the --watch flag. I have defined two scripts in package.json as follows: "test": "mocha", "test:watch": "mocha --watch ./test ./game_logic" When I run ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Having trouble accessing the value of an <asp:HiddenField> using javascript

Currently, I am setting a value to a hidden field and attempting to retrieve that value in my JavaScript code. In the declarative part of my code: <asp:HiddenField ID="chkImages" runat="server" /> <div id="main" runat="server" style="display:non ...

Cannon.JS ensures that walls are impenetrable

I am currently experimenting with three.js and cannon.js, but I have encountered an issue where I am unable to create solid walls or any stationary objects that can block the player's movement. Below is the code I have been working on so far. I would ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Using the conditional rendering technique in a mapped function within a React table cell

I have an array that is being displayed inside a Table, and I need to compare each object's "userName" property with the header in order to determine where to place the value. If there is no match, it should display a "0". Here is a snippet of the ta ...

While utilizing the json_encode() function, Ajax encountered a 500 Internal Server Error

My attempt to implement a basic Ajax request using JS and PHP did not go as planned. Here is the code I used: test.js $(document).ready(function () { $.ajax({ url: window.location.href + 'test.php', type: 'GET', ...

Finding differences between two 24-hour format times using moment.js

Is there a way to compare two times in 24-hour format using the code below? $("#dd_start_timing, #dd_end_timing").on('keyup change keydown', function() { var DutyDayStartTime = $("#dd_start_timing").val().trim();// 13:05 var ...

What is the best way to reference a div link from a different PHP file?

Struggling to access a page div from another php file, I've tried calling it using (found online) admin.php#changepass Here's an example of my HTML code: <div id="changepass" class="w3-container city" style="display:none"> <form name ...

What reasons could explain why the more efficient approach of offering an initial portion of data is not faster in practice?

My website contains numerous pages with a plethora of small images that need to be loaded. To enhance user experience, I devised two methods to first display a subset of the content without waiting for the entire page to load. The data is stored in a .json ...

Connection to Mysql database terminated for Node.js

I'm currently working on integrating a basic form into my database to enhance my understanding of node.js. However, I keep encountering an intriguing error during the process... error when connecting to db: { [Error: Connection lost: The server close ...

Troublesome code with Ajax, Jquery, and PHP is causing issues

I've been trying to send an array from php to js using ajax, but for some reason it's not working no matter what I try. I'm convinced it must be a simple fix, but I seem to have exhausted all my options. <!doctype html> <html lang= ...

After the submit button is disabled, the form fails to be submitted

Hello, I am having an issue with disabling my button after the form is submitted. The button gets disabled, but the PHP code does not execute. I have tried various scripts from the internet, but they all seem to have the same result: the button gets disab ...