0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.