* Private method to run the actual conversion of array of objects to CSV data. * @param {object[]} data * @param {boolean} header - Whether the first line should contain column headers. * @param {boolean} allColumns - Whether to check all items for column names. * Uses only the first item if f
(data, header = true, allColumns = false)
| 107 | * @returns {string} |
| 108 | */ |
| 109 | async function convert(data, header = true, allColumns = false) { |
| 110 | if (data.length === 0) { |
| 111 | return ''; |
| 112 | } |
| 113 | |
| 114 | const columnNames = |
| 115 | allColumns |
| 116 | ? [...data |
| 117 | .reduce((columns, row) => { // check each object to compile a full list of column names |
| 118 | Object.keys(row).map(rowKey => columns.add(rowKey)); |
| 119 | return columns; |
| 120 | }, new Set())] |
| 121 | : Object.keys(data[0]); // just figure out columns from the first item in array |
| 122 | |
| 123 | if (allColumns) { |
| 124 | columnNames.sort(); // for predictable order of columns |
| 125 | } |
| 126 | |
| 127 | // This will hold data in the format that `async-csv` can accept, i.e. |
| 128 | // an array of arrays. |
| 129 | let csvInput = []; |
| 130 | if (header) { |
| 131 | csvInput.push(columnNames); |
| 132 | } |
| 133 | |
| 134 | // Add all other rows: |
| 135 | csvInput.push( |
| 136 | ...data.map(row => columnNames.map(column => row[column])), |
| 137 | ); |
| 138 | |
| 139 | return await csv.stringify(csvInput); |
| 140 | } |
| 141 | |
| 142 | function displayTextGenerationCode() { |
| 143 | $('#code-snippet').show(); |