Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export array of dynamic JSON objects to CSV in Angular?

I am trying to export an array of JSON objects to CSV than can vary in the amount of key-value pairs (meaning some can have additional columns than the rest). I am currently able to export using Angular2CSV package but it only supports given all the columns are included.

The code below shows my current implementation where service returns the data to be downloaded.

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

        });
    }
like image 558
caricature Avatar asked Aug 02 '26 17:08

caricature


1 Answers

Based on this issue (https://github.com/javiertelioz/angular2-csv/issues/27) you might find inspiration for a more dynamic solution:

The isolution for the issue has something like:

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

Based on this :

Create a set to contain unique headers:

let headerSet = new Set();

For every row in the response, get the keys of that line and add them to the set (pseudo-code)

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

For the data part, you have to re-run the process and check for every line whether or not it has a certain key and if not you need to put and empty value or something you like with that missing key (it's tricky since all the values need to be inserted in the correct order, so a Set solution alone, might not be enough).

When all possible headers/data are/is added:

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

The exact code needs to be composed. I didnt check nor do I know what the data format is.

like image 158
jcuypers Avatar answered Aug 04 '26 05:08

jcuypers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!