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

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...

Include a header in the API HTTP call for Angular 2 and Ionic 2

Working on my Ionic 2 app, I am using Angular 2 Http to retrieve JSON from an API. However, I am struggling to send the app-id, app-key, and Accept as headers in the main code snippet below: import {Component} from '@angular/core'; import {NavC ...

Creating a peaceful web platform with React that supports several user roles

I am in the process of developing a single-page web application that must be completely restful, which is new territory for me. One challenge I'm facing is determining how to efficiently render the user interface for different roles using React. With ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...

Looking to split the month and year input boxes when utilizing stripe version 7.2.0

Currently, I am utilizing ngx-stripe Version 7.2.0 to manage UI elements in Angular. I'm wondering if there is a method to split the Month and Year into separate text boxes within the UI of Angular 7 instead of having them combined into one field? ...

Unable to modify an attribute due to TypeScript error: Type 'string' cannot be assigned to type 'never'

I am trying to modify an attribute of an object in TypeScript and React, but I keep encountering the following error message: Type 'string' is not assignable to type 'never'. This happens even though I have a check in place to verify th ...

Navigating through drop-down menus using jQuery

I need help with a JavaScript script that can calculate the total number of points based on selected checkboxes and dropdown values. Currently, my script is able to iterate through checkboxes and assign 1 or 2 points based on their classes, but I'm st ...

Verify if there are duplicate values present in a table

I have a Table that contains multiple rows, each row having input fields. I need to check for duplicate values within the table. Below is my code where I am currently checking for empty values, how can I modify it to also detect duplicate values? JavaScr ...

The iframe is set to take the source URL from url.com/id using the "id" parameter

Currently, I am attempting to set the src of an iframe by extracting the URL from the toolbar address. The URL consists of the domain plus an ID, which happens to be the same as the YouTube ID. For instance: www.youtube.com/watch=id In my case, my domain ...

Remove all duplicate lists from JSON data

Currently seeking more information about a particular issue I am facing. I have already explored JSON encoding/decoding, but it did not provide the exact solution I need. I am looking for an efficient way to extract data from a list like this: //response ...

Issue with setTimeout() function not being triggered within a VueJS method

I am currently developing an application that allows a user to reset or shutdown a particular server. I am focused on creating the interface and ensuring that the user receives appropriate messages about the actions being taken. My approach involves displa ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...

There seems to be a problem with the output when trying to display the message "You said ${reply}"

In the following code snippet, vanilla.js is being used with ATOM as the text editor and running on nodejs via terminal: 'use strict'; const Readline = require('readline'); const rl = Readline.createInterface({ input:process.stdin, ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

Using Node to parse XLSX files and generate JSON data

Hello, I am currently utilizing the js-xlsx package which can be found at this link. My inquiry is how to successfully parse an xlsx file with merges and convert it into JSON format. You can view what the excel sheet looks like here. Ultimately, the JSON o ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

Achieving the perfect sorting result in an array using Javascript

I am attempting to arrange the objects inside an array below in ascending order by their values and achieve the desired output as shown: var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.004186044328301671376196 ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

What is the best way to update the div id by extracting the last digits from a number?

Is there a way to change the div ids using a function? Before: <div id="a_1">a1</div> <div id="b_1">b1</div> <div id="c_1">c1</div> <div id="d_1">d1</div> <button onclick="change()">Change</button& ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...