Tips for exporting an array of dynamic JSON objects to CSV using Angular

I am facing a challenge in exporting an array of JSON objects to CSV as the number of key-value pairs can vary, leading to additional columns in some objects. Currently, I am using the Angular2CSV package for export functionality, but it requires all columns to be included.

Below is the code snippet that showcases my current approach where the service provides the data to be downloaded.

private exportTable(){
        this.service.exportDataForDownload().then(response => {
            let csvFileName = "Results";
            new Angular2Csv(response, csvFileName, {headers: this.tableheaders});

        });
    }

Answer №1

After reviewing the details in this discussion (https://github.com/javiertelioz/angular2-csv/issues/27), you may discover inspiration for a more adaptable solution:

The resolution provided suggests something similar to:

new Angular2Csv(this.data, 'myCsv', { headers: Object.keys(this.data[0]) });

In consideration of this approach:

Create a collection to store distinct headers:

let headerSet = new Set();

For each row in the response, retrieve the keys of that row and include them in the set (pseudo-code)

for (r of/in response) {
    headerSet.add(Object.keys(r));
}

Regarding the data segment, you must repeat the process and verify for every row whether it contains a certain key. If not, you will need to insert an empty value or a preferred alternative for that missing key (it can be challenging as all values must be placed in the right sequence, so relying solely on a Set solution might not suffice).

Once all potential headers/data have been included:

new Angular2Csv(response, csvFileName, {headers: Array.from(headerSet});

The specific code needs to be constructed. I haven't verified nor do I possess knowledge of the data format.

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

Enhance your website design with a custom content scroller using Bootstrap and

Having trouble getting this plugin to work with bootstrap on my website. Does anyone have a solution for this issue? Alternatively, does anyone know of another approach I could take? UPDATE: I managed to fix the problem myself. Add the following code ...

Securing a route using a referrer in Node.js: Best practices

Within my node.js application, I am looking to secure a specific route so that users can only access the page /post if they are coming from /blog. If the user accesses the route from any other source, they should be redirected to /. I have implemented the ...

Achieving a scrollable div with ng-repeat

I have implemented ng-repeat to showcase some messages, and I am attempting to create a scrollable "message_area" as the messages overflow naturally over time. However, my current code is not delivering the desired outcome. <div class="main_area"> ...

Developing a declaration for an unnamed function in a JavaScript file

module.exports = function (argument1, argument2) { return { myFunction } function myFunction () { ... } } What is the process for creating a TypeScript declaration file for this specific JavaScript file? ...

Ways to inform a subelement that a task is complete?

I have a child component that displays a list of orders passed from the parent. I want to include a "Reload" button inside the child component that, when clicked, triggers a function in the parent component to reload the orders. Upon clicking the reload b ...

Updating the appearance of tabs in React Native Navigation dynamically during runtime

I am currently working with the startTabBasedApp API, which includes three tabs in my app. I have a requirement to change the background color of the tabBar for specific screens dynamically. Is it possible to achieve this at runtime? For instance: Scree ...

Verifying if any of the entries in a specific index contain a null value

Here is the structure I am working with: { "subs": [ { "status": "1", "run_settings": null, "ward": "/asda/asd/ada" "value": null, "name": null }, { "status": "0", "run_settings": null, "ward": ...

At what point is a $.cache considered oversized?

After coming across a fascinating tutorial, I learned that certain memory leaks in jQuery can be identified by monitoring the size of the $.cache variable. It was emphasized to always keep an eye on its size, as it could indicate potential issues if it bec ...

Steps to update XmlHttpRequest URL during image upload

I am currently facing an issue with updating images on my website. When I try to update an image, it redirects to the wrong URL instead of the intended one. The form is set to post data to this URL: POST http://127.0.0.1/mgt/upload/processImage/foodImage ...

What might be causing the issue in the build process of my next.js project?

**Why is my Node.js YAML file causing an error?** name: Node.js CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-ver ...

Challenges encountered with autofill and a null string

When I try to fetch data from the server for autocomplete, it returns no options even though two options are displayed in the console after making an API call. The value I enter includes two empty spaces followed by 'IPH', triggering the API call ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

Discover and eliminate the style attribute through a click action

I've been struggling to find a solution to remove the style attribute from a specific tr tag within a table when it is clicked. I've tried several lines of code but none seem to work. Here's the link to the fiddle for reference: http://jsfi ...

Angular 8 utilizes JavaScript for its programming language

Looking for a solution in JavaScript - check out: codepen.io/skovtun/pen/VwLvXPB Struggling to find an equivalent for Angular 8+. I want the center block to maintain a fixed width of 1200px, and automatically compress when the left, right, or both sideb ...

Surfing the web with Internet Explorer means music downloads rather than streaming

My music website functions properly, however I am experiencing issues when accessing it through Internet Explorer. The internet download manager is downloading music from the site without any problems in Chrome and Firefox. Is there a way to prevent or b ...

Exploring a different approach to utilizing Ant Design Table Columns and ColumnGroups

As per the demo on how Ant Design groups columns, tables from Ant Design are typically set up using the following structure, assuming that you have correctly predefined your columns and data: <Table columns={columns} dataSource={data} // .. ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Designing a versatile Angular component for inputting data (Mailing Address)

Currently, I am in the process of developing an Angular 11 application that requires input for three distinct mailing addresses. Initially, I thought I had a clear understanding of what needed to be done, only to encounter warnings about elements with non- ...