"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as "[object object]" in the CSV file.

TS file:

getData() {
   let source = this.resultList;
   let destination = [];
     for (let i = 0; i < source.length; i++) {
         let entry = new Entry();
         entry.id = source[i]['id'];
         entry.participantId = source[i]['participantId'];
         entry.completedOn = moment(source[i]['completedOn']).format('DD/MM/YYYY');
          if (typeof source[i]['satisfaction'] == 'string') {
              entry['satisfaction'] = source[i]['satisfaction']
            } else {
                for (var property in source[i]['satisfaction']) {
                    if (source[i]['satisfaction'].hasOwnProperty(property)) {
                     entry[property] = source[i]['satisfaction'][property]
                    }
            }
          }
         destination.push(entry);
     }
     return destination;
    }

I am struggling to extract objects present in "prodandService" to the CSV file - they are being displayed as "[object object]" instead of the actual items.

JSON data:

{"satisfaction":{"prodandService":[{"index":"Orbiz"},{"index":"qwerq"},{"index":"asfd"},{"index":"test"},{"index":"test123"},{"index":"TestWD"},{"index":"IOS app"},{"index":"Lipstick"},{"index":"Foundation"},{"index":"lipstick"},{"index":"Website"},{"index":"App IOS"},{"index":"Shampoo Vanilla"},{"index":"Shampoo Strawberry"},{"index":"car"},"Lipstick"],"price":"medium","customer":"yes","recomondation":"4","sales":["phone"],"phoneVist":"3","importance":["Quality"],"frequence":"quarter","satisfaction":"3"},"completedOn":"2017-08-28T09:39:54.676Z","id":10,"participantId":217}

I would greatly appreciate any assistance with this issue.

Answer №1

Utilizing a library for exporting to CSV files proved to be highly effective for me:

In my Angular4 application, I have incorporated an external library for document exportation: https://github.com/eligrey/FileSaver.js/

Below is the excerpt of code I implemented to extract my data. I linked this method to a button for triggering the event:

TypeScript component : (EDITED)

  // Pay attention to the parameters received from the service call that provide the filtered data
  exportDatas(documentType: string) {
    // Presuming you have stored the service data you wish to export in this.resultList
    let source = this.resultList;
    const blob = new Blob([source.blob()]);
    const objectUrl = URL.createObjectURL(blob);
    FileSaver.saveAs(blob, 'Export.' + documentType);
  }

Template side : (EDITED)

<div>
  <button (click)="exportDatas('csv')" type="button">CSV</button>
  <button (click)="exportDatas('pdf')" type="button">PDF</button>
</div>

Functioning seamlessly, and the code is now easier to maintain.

EDIT :

Installation via NPM :

  • npm install file-saver --save
  • npm install @types/file-saver --save-dev
    (Adding types if required, although not utilized by me)

Ensure to import it into your component (particularly when using Angular-CLI) :

  • Without types :
    import * as FileSaver from 'file-saver';
  • With types (not tested but should work) :
    import { FileSaver } from 'file-saver';

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

It is not possible to execute an injectable function using a service instance, as the parameter value consistently stays as null

I am utilizing an angular web app that relies on access tokens that have the potential to expire. When they do expire, a 401 status response is sent back to the app, triggering processing by a retryWhen operator. The logic for initiating a token refresh AP ...

Securing routes in Angular without relying on LocalStorage or Cookies by implementing an Auth Guard

Currently, I am working on implementing an authentication guard in Angular. Instead of the conventional method of checking local storage or cookies to verify user authentication, I am utilizing API endpoints that respond with 200 OK if a httponly cookie co ...

Can someone explain the significance of this error message in Redux - Toolkit?

Encountered this error message while working with Redux-Toolkit, could someone explain its meaning? name:"ConditionError" message:"Aborted due to condition callback returning false." ...

Creating a jQuery countdown script

Is it possible to easily convert the function below into jQuery and still maintain the ability to call multiple instances of the countdown? This particular function receives a server time echoed by the server and then initiates a countdown to the specifie ...

Ensure CSV file does not contain any blank lines during reading or writing operations

I have a challenge where I need to display the contents of a CSV file row by row. The issue is that there is only one row of data in the file, but for some reason, the CSV Library adds an extra row at the end. When I print the contents, it shows up twice b ...

Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations. To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that. To simplify matters, I ...

Undefined Response Error when Utilizing Dropzone for File Upload in Express

I am currently in the process of setting up a basic image upload demonstration using Dropzone and Express. Here is what my form looks like: <form id="ul-widget" action="/fileupload" class="dropzone" enctype="multipart/form-data"> <div class="fal ...

Traversing JSON data structures regardless of missing keys

Here is a JSON containing some data: { "results":[ { "name":"Sydney Showboats", "photos":[ { "photo_reference":"Pic062" } ] }, ...

Combining PHP code within JavaScript nested inside PHP code

I am currently facing an issue with my PHP while loop. The loop is supposed to iterate through a file, extract three variables for every three lines, and then use those variables to create markers using JavaScript. However, when I try to pass the PHP varia ...

Using the v-for directive before applying the Vue directive

I need help with displaying images in a carousel from data fetched via Firebase. I have created a directive, but the problem lies with the v-for loop. The directive is executed before the v-for loop, resulting in no items in the carousel. Directive: di ...

Can the output object from an angular form validator be obtained and utilized?

As per the documentation, The validator is capable of returning an object {[key: string]: any} or null This implies that it can return an object (for any) which includes detailed information about what went wrong during validation. For example: function ...

Exploring techniques to retrieve data from Json Array in Angular using Firebase documentation

this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe(); When I include it in my component.html file like this: {{ currentUser$|async|json}} The output I get is as follows: { "photoUrl": "", &qu ...

What is the best way to set up a sidenav with router-outlet and a distinct login page with router-outlet?

My goal is to create an application with a login page that, once the user logs in, displays a navbar, toolbar, and sidenav with a router-outlet. In my app.component.html, I have set it up like this: <div *ngIf="isAuthenticated"> <app- ...

Server Sent Events not being received by client from Express.js server

My Next.js (React) client is set up to receive Server-Sent Events from my Node.js/Express.js server, but it seems like it's not receiving any messages for some unknown reason. While the open and error events of EventSource are functioning correctly, ...

Transform JSON-serialized string with HTML entities into an object

Looking for a solution to convert the following string into an object using Javascript: "[&quot;Software&quot;,&quot;3rd Party&quot;]" While I know how to convert HTML Entities to DOM Objects with this code: $("<div/>").html(encode ...

Activate the script upon the left-click of the arrow icon

Looking for help with this basic javascript code snippet. $('#about_us').on('click',function() { $('#slider').toggleClass('open'); }); I'm trying to find a way to activate this function by pressing the lef ...

Is it possible to eliminate any leftover comments from a JSON string using jQuery and Ajax?

Having an issue with a framework that generates invalid JSON String like this: /* { "myobject" : "test"} */ The problem lies in the comments before and after the json string. This is done for security purposes, as it's not recommended to return JSON ...

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...

What is the best way to store and retrieve all the variable data from a .js file on a user's device?

I'm looking for a way to save and load multiple variables in JavaScript that determine a "save" state. These variables are stored in a file named "variables.js." Is there a simple method to easily save all the information in this file and then load i ...