Convert Object into CSV?

Hey everyone, I’m having a tough time wrapping my head around this one. I have some data object with properties and each property has an array as a value. Here is an example of the data:

     {
     'Prop 1 (Col Header 1, Row 1)':
       [
         'String value (Col 1, Row 2)',
         'String value (Col 1, Row 3)',
         'String value (Col 1, Row 4)',
       ],
       'Prop 2 (Col Header 2, Row 1)':
         [
          'String value (Col 2, Row 2)',
          'String value (Col 2, Row 3)',
          'String value (Col 2, Row 4)',
         ]
       }

I have tried to make it clear what needs to happen. The properties in the object need to be the column headers and the array values need to be under each column. I had tried so many things by unshifting the column headers into their own arrays, separating values at commas to go to a new cell in combination with splitting the arrays and joining them by .join('\n') to go to the next row. I am not quite sure how to tackle this issue. Perhaps a hash table?

The easy solution would be to have the arrays of each row, however I don’t think the data would work properly in that situation. Any help or experience with converting to CSV strings would be great.

Hi there @rstorms

Hopefully I have understood what you are trying to do here. My understanding of your problem is that you have an object in the form:

const obj = {
  a: [1, 2, 3],
  b: [4, 5, 6],
  c: [7, 8, 9],
};

And you want to convert it to comma separated values in the form:

/*

a,b,c
1,4,7
2,5,8
3,6,9

*/

Assuming all the arrays have equal length, then the code below should generate a string of comma separated values you are looking for.

const rows = [Object.keys(obj).join(',')];

const cols = Object.values(obj);

for (let row = 0; row < cols[0].length; row++) {
  const currentRow = [];
  for (let col = 0; col < cols.length; col++) {
    currentRow.push(cols[col][row]);
  }
  rows.push(currentRow.join(','));
}

const csv = rows.join('\n');
console.log(csv);

Hopefully that answers your question.

1 Like

You are absolutely incredible, thank you so much. Gonna have to dig into this to understand exactly what you did!!!

EDIT: Thanks for this solution. I absolutely understand it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.