Issue
I am trying to convert some object into string so I have save it into a csv file.
Right now my code with save this string data into a .csv file and it will work.
csvdata = `Date,"First Name","Last Name","Email"
08.22.2019,"Simon","Grimm","saimon@devdactic.com"
08.21.2019,"Simon","Grimm","saimon@devdactic.com"
08.19.2019,"Simon","Grimm","saimon@devdactic.com"
08.18.2019,"Simon","Grimm","saimon@devdactic.com"
08.17.2019,"Simon","Grimm","saimon@devdactic.com"
08.16.2019,"Simon","Grimm","saimon@devdactic.com"`;
My issue is that I need to convert an array of objects into the above.
Searching google I read that I can convert an object into a blob:
So I tried:
objToBlob() {
const obj = {hello: 'world'};
const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'text/csv;charset=utf-8;'});
console.log(blob);
}
But if I do blob.toString();
and save that into the csv file I get [Object Blob] inside the first cell.
So that doesn't work.
Any ideas on how I can do this baring in my the the csvData when saved inside the .csv file will work but I need to have an object but it needs to be a string when saved.
How can I do this?
I'm using Angular / Ionic 5 BTW.
Solution
You can convert the object to comma separated values and then use it just just like you were using the csvdata
. For example:
const obj = {hello: 'world', hi: 'earth'}
const result = Object.keys(obj).map(key => key + ',' + obj[key])
console.log(result.join(" \n"))
/*
"hello,world
hi,earth"
*/
As you can see, the result is just like your csv data
Update: If the data is an array:
const car = [ { make: 'Steve', model: 'Celica' }, { make: 'Porsche', model: 'Boxter' }, ];
const obj = {hello: 'world', hi: 'earth'}
const convertToCSV = (obj) => Object.keys(obj).map(key => key + ',' + obj[key]).join(" \n")
const result = car.map(x => convertToCSV(x)).join()
console.log(result)
/*
result:
"make,Steve
model,Celica,make,Porsche
model,Boxter"
*/
Answered By - Alf Moh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.