Search code examples
javascriptexport-to-csvpapaparse

Change column name while unparsing using Papa parser


I have a array of object which i want to convert it into CSV format using Papa Parser javascript library.

so far I am able to convert the array of object using Papa.unparse function but the issue with this is column name. Is there a way to provide the custom column name in Papa.unparse function so that I do not have to clone my existing array of object into to another array of object with altered column name.

    var csvVal = Papa.unparse(callHistoryArray,{
                    quotes: false, //or array of booleans
                    delimiter: ",",
                    header: true,
                    newline: "\r\n",                        
                    columns: [
                            "_name",
                            "_number",                          
                            "_type",
                            "_mode",
                            "_duration",
                            "_objType",
                            "_dateTime"

                    ], //or array of strings


                }
        );

it generates following output

_name,_number,_type,_mode,_duration,_objType,_dateTime
Willey W,2314651324,outgoing,,0:50,Contact,1573553784000

Instead of this I am expecting

'Name','Number','Type','Mode','Duration','Entity','DateTime'
Willey W,2314651324,outgoing,,0:50,Contact,1573553784000

Solution

  • You can choose not to create a header when parsing the data, and then create a header an concat them.

    Example:

    var callHistoryArray = [{ a: 1, b: 2 }, { a: 3, b: 4 }];
    
    var csvVal = Papa.unparse(callHistoryArray, {
      header: false,
      columns: [
        "a",
        "b",
      ], //or array of strings
    });
    
    var headersVal = Papa.unparse({ fields: ['id', 'value'], data: [] });
    
    var result = headersVal + csvVal;
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.js"></script>