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
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)
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With