Export JSON data to CSV file using AngularJS

Whenever I attempt to download filter data in ng-table to CSV, I encounter an issue where a single row is being split into two rows.

The expected output should look like this

Row1 consists of three columns:

Item 1 | 12222-12228-14567-124568-18680-20940-18717-ABCDED-sdf_dsfsdf | X-Large

However, the actual result looks like this:

1st row

Item 1 | 12222-12228-14567-124568-18680-20940-18717-ABCDED-sdf_dsfsdf |

2nd row

X-Large

This discrepancy is causing confusion. Here is a snippet of my code:

var data = [{ "name": "Item 1", "color": "12222-12228-14567-124568-18680-20940-18717-ABCDED-aSFDasdf_sdfsdf_dsfsdf", "size": "X-Large" },
     { "name": "Item 2", "color": "Green", "size": "X-Large" },
     { "name": "Item 3", "color": "Green", "size": "X-Large" }];

$scope.downloadData = function (data){
       var csv = $scope.JsonToCsv(data);         
}

$scope.JsonToCsv = function(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) :objArray;
        var str = '';
        var line = '';
        var head = array[0];
        for (var index in array[0]) {
            var value = index + "";
            line += '"' + value.replace(/"/g, '""') + '",';
        }
        line = line.slice(0, -1);
        str += line + '\r\n';
        for (var i = 0; i < array.length; i++) {
            var line = '';
            for (var index in array[i]) {
                line += array[i][index] + ',';
            }
            line = line.slice(0, -1);
            str += line + '\r\n';
        }
        return str;
    }

I would greatly appreciate any assistance in identifying what might be causing this issue within my code. Thank you!

Answer №1

I successfully modified the code to meet your requirements. I hope it functions as expected for you.


var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = "";
for (var index in array[0]) {
    line += index + ',';
}
line = line.slice(0, -1);
str += line + '\r\n';
for (var i = 0; i < array.length; i++) {
    var line = "";
    for (var index in array[i]) {
        line += '"' + array[i][index] + '",';
    }
    line.slice(0, line.length - 1);
    str += line + '\r\n';
}
if (str == '') {
    alert("oops");
    return;
}
console.log(str);
return str;

Thank you :)

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 class selectors does not have any effect on newly added items

Imagine you have a ragged array structured as shown below: var myarray = [ [ ['k1', [] ], ['k2', ['l1', 'l2'] ], ['k3', [] ], ], [ ['k1', [] ], ['k2', ['l1', 'l2&ap ...

Package for running scripts in Node Package Manager

Currently, I am working on developing an npm package that will automatically insert a specific npm script into any package.json file that it is being used. Unfortunately, after going through the npm package.json/script documentation, I haven't been ab ...

Error in Prestashop 1.7: jQuery is not found in product details

Whenever I access the product detail page, a console error pops up. "Uncaught ReferenceError: jQuery is not defined" This issue only occurs on these specific pages. I've attempted to add the necessary dependency through both the head.tpl ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Retrieving the value of onCheck from the Checkbox/ListItem

Imagine I have a React.Component that displays components from material-ui: {data.map(value => ( <ListItem key={data.indexOf(value)} primaryText={value} leftCheckbox={ <Checkbox onCheck={this.pr ...

Error encountered during execution of Angular application, specifically TS2305 error?

Hello, I am currently running an angular application by using the 'ng serve' command. I encountered the following error: ERROR in src/app/accounts/account-form/account-form.component.ts(29,3): error TS2305: Module '"/home/prasanth/primecas ...

Unlimited Cycle using Vue Router Global Precautionary Measures

Currently, I am facing an issue with redirecting users using Firebase Auth and Vue Router. The problem arises when the Router redirects the user to '/' as it results in a blank white screen on the website. I am aware that there is an error in m ...

Troubleshooting problem with modifying Bootstrap button styling and hover effects

When creating a navigation menu with Bootstrap, I decided to change the buttons from the primary class to inverse. I then went on to further customize the inverse class using inline CSS to match my specific look and feel requirements. .btn-inverse { b ...

Using Vue to perform multiplication on data table entries

Is there a way I can use Vue.js to multiply values in a table? The values provided are for 100g of the product. For example, if I input 200g, I would like the values to double: 318kcal, 12 fat, 48 carbs, 8 protein, and 2% iron. Similarly, inputting 50g sho ...

What kind of mischief can be wreaked by a malicious individual using JavaScript?

My mind has been consumed by thoughts about the safety of my projects, especially when it comes to password recovery. On the password recovery page, users must fill out a form with valid data and complete a recaptcha test for security. To enhance user ex ...

I require a superscript character in the center of a string within an array for my Android application

I have explored numerous options for my specific requirement, but none seem to be suitable or straightforward enough for me to implement without difficulty. In my list view, there are only a few instances where I need to use superscript 6. However, I am s ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

Displaying the focus icon on the active tab using Angular Material

I am currently utilizing Angular material to dynamically generate tabs in my HTML code. I'm trying to display a drop arrow icon on the active or selected tabs, but I am facing some challenges with the implementation. Below is the code snippet I have ...

Is it possible to single out a specific cell with the smart-table feature?

While the smart-table documentation provides instructions on selecting a row of data, it does not cover selecting an individual cell (the intersection of a row and a column). Upon further research, I came across this discussion where the project owner men ...

I am looking for string validation in Angular

Hello, I have just one input box where I enter a 10-digit string, and I am looking to apply the following validations to the entered string: The first 4 characters should be alphabets The characters from 5 to 9 should be numeric The last character should ...

Showcasing JSON information on an HTML webpage depending on the URL parameters provided

I am attempting to achieve the following using HTML and Javascript exclusively. Once users submit my form, their data is added to a confirmation page in this format: On that page, I aim to display all locations from locations.json with a country matching ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

Is the process of converting text to PNG and then reading it as a stream all completed on the front-end?

Is it feasible to achieve the following task? Allow the user to input text Generate a PNG from the entered text Upload the PNG to Pinata, in ReadStream format Perform all of these actions on the front-end Steps (1) and (2) have been successfully complete ...

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...