Mohammed Amin
Mohammed Amin

Reputation: 1

Generating CSV, array of numbers inside one column

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

Upvotes: 0

Views: 154

Answers (1)

Wamiq Rehman
Wamiq Rehman

Reputation: 566

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"))

Upvotes: 1

Related Questions