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
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
Share Improve this question edited Jul 8, 2019 at 3:43 user6269864 asked May 9, 2018 at 15:31 John DoeJohn Doe 1831 silver badge7 bronze badges 04 Answers
Reset to default 14If 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 that thing (myObject
) is a JavaScript object, you can serialize it in array chunks using destructuring and then join them in a string using Array#reduce
:
const data = {
'0': {
timestamp: 1525879470,
name: "testing",
lastname: "testingdone"
},
'1': {
timestamp: 1525879470,
name: "testing2",
lastname: "testingdone2"
}
};
const result = [
// headers
Object.keys(data['0']),
// values
...Object.values(data).map(item => Object.values(item))
]
.reduce((string, item) => {
string += item.join(',') + '\n';
return string;
}, '');
console.log(result);
Be careful about writing your own code for CSV, there are a lot of edge cases and much more than just combine items with a comma and a newline (what if your data contains commas? how to insert the BOM to make sure your text with a non-ASCII input displays correctly in any spreadsheet software?).
Here's some working example code:
const ObjectsToCsv = require('objects-to-csv');
// Sample data - two columns, three rows:
const data = [
{code: 'HK', name: 'Hong Kong'},
{code: 'KLN', name: 'Kowloon'},
{code: 'NT', name: 'New Territories'},
];
// If you use "await", code must be inside an asynchronous function:
(async () => {
const csv = new ObjectsToCsv(data);
// Save to file:
await csv.toDisk('./test.csv');
// Return the CSV file as string:
console.log(await csv.toString());
})();