Sometimes, we want to convert JavaScript array to CSV.
In this article, we’ll look at how to convert JavaScript array to CSV.
How to convert JavaScript array to CSV?
To convert JavaScript array to CSV, we use array and object methods.
For instance, we write
const data = [
{ title: "Book title 1", author: "Name1 Surname1" },
{ title: "Book title 2", author: "Name2 Surname2" },
{ title: "Book title 3", author: "Name3 Surname3" },
{ title: "Book title 4", author: "Name4 Surname4" },
];
const csv = data
.map((d) => {
return Object.values(d).join(",");
})
.join("\n")
to call data.map
with a callback that gets the values from each object in data
with Object.values
.
Then we call join
to join the values into a string with each entry separated by a comma.
Then we call join
again to combine the strings into a CSV with each line separated by a new line character.
Conclusion
To convert JavaScript array to CSV, we use array and object methods.