Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a collection of objects to CSV with keys as headers and values

Tags:

javascript

csv

I have an object myObject like this

 0:
    timestamp: 1525879470
    name: "testing"
    lastname: "testingdone"
 1: 
    timestamp: 1525879470
    name: "testing2"
    lastname: "testingdone2"

I am looking for a way to convert it to csv nicely like this

timestamp,name,lastname
1525879470,testing,testingdone
1525879470,testing2,testingdone2

Good news is I can extract the header

var headers = Object.keys(myObject.reduce(function (result, obj) {
                            return Object.assign(result, obj);
                        }, {}));

The headers var will give me an array of headers like

Array(3): timestamp, name, lastname

I am just looking to extract the values from the object maybe in an array like header, and then finally convert it into CSV as above. I tried using array map but for some reason I am not able to figure it out

like image 263
John Doe Avatar asked May 09 '18 15:05

John Doe


2 Answers

If that is array of objects you can first get header and then values and create string from that.

const data = [ {timestamp: 1525879470,name: "testing",lastname: "testingdone"
}, {timestamp: 1525879470,name: "testing2",lastname: "testingdone2"}]

let csv = '';
let header = Object.keys(data[0]).join(',');
let values = data.map(o => Object.values(o).join(',')).join('\n');

csv += header + '\n' + values;
console.log(csv)
like image 164
Nenad Vracar Avatar answered Sep 23 '22 17:09

Nenad Vracar


A more simplified approach based on the examples above

// Sample data - two columns, three rows:
const data = [
  {code: 'HK', name: 'Hong Kong'},
  {code: 'KLN', name: 'Kowloon'},
  {code: 'NT', name: 'New Territories'},
];

// Transform an array of objects into a CSV string
const csv = function(data) {
  // Setup header from object keys
  const header = Object.keys(data[0]).join(",");

  // Setup values from object values
  const values = data.map(item => Object.values(item).join(","));

  // Concat header and values with a linebreak
  const csv = [header, ...values].join("\n");

  return csv;
};

// Setup file
const file = csv(data)

console.log({ file })
like image 30
Andréas Blondeau Avatar answered Sep 26 '22 17:09

Andréas Blondeau