I'm trying to generate a CSV file using javascript
my data shape is:
const data = [
{ name1: [111, 222] },
{ name2: [333, 444] }
];
the goal is getting the following result inside a csv file:
name1, name2
111, 333
222, 444
,555
CodePudding user response:
This should help you. For more tidy approach you can also use reduce function
const data = [{
name1: [111, 222]
}, {
name2: [333, 444, 555]
}];
//Get all the headers
var headers = data.map((e) => {
const header = Object.keys(e)[0];
return header;
});
//Get all the values
var values = data.map((e) => {
const l = Object.values(e)[0];
return l
});
//Get the max length of the arrays
var maxLen = Math.max(...values.map((e) => {
return e.length;
}));
var csvData = [];
for (var i = 0; i < maxLen; i ) {
var row = headers.map(function(n, j) {
if (data[j][n]) {
return data[j][n][i]
}
}).join(",")
csvData.push(row);
}
var csvHeader = headers.join(",")
//Print data
console.log(csvData.join("\n"))
//Print data with header
console.log(csvHeader "\n" csvData.join("\n"))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>