Here is the provided data:
result =
[
{
"Id":"0012v00002InPVmAAN",
"Test__c":"India; Africa; Mombasa",
"Test1__c":"AFR; TFR; GFR"
}
]
I want to convert the above data into a CSV file by splitting the semicolon separated values (Test__c & Test1__c) into multiple rows along with other data.
"Id,Test__c,Test1__c --> csv file column header
"0012v00002InPVmAAN","India","AFR"
"0012v00002InPVmAAN","Africa","TFR"
"0012v00002InPVmAAN","Mombasa","GFR"
In JavaScript -
this.data = result
downloadCSVFile() {
let rowEnd = '\n';
let csvString = '';
// This set eliminates any duplicate keys
let rowData = new Set();
this.data.forEach(function (record) {
Object.keys(record).forEach(function (key) {
rowData.add(key);
});
});
rowData = Array.from(rowData);
csvString += rowData.join(',');
csvString += rowEnd;
for (let i = 0; i < this.data.length; i++) {
let colValue = 0;
for (let key in rowData) {
if (rowData.hasOwnProperty(key)) {
let rowKey = rowData[key];
if (colValue > 0) {
csvString += ',';
}
let value = this.data[i][rowKey] === undefined ? '' : this.data[i][rowKey];
csvString += '"' + value + '"';
colValue++;
}
}
csvString += rowEnd;
}
I attempted the code above, but it is combining (Test__c & Test1__c) values into a single row.
How can I properly create a CSV file by splitting the semicolon separated values (Test__c & Test1__c) into multiple rows along with other data?