To convert JSON object to CSV format in JavaScript, we use some object and array methods.
For instance, we write
const convertToCSV = (arr) => {
const array = [Object.keys(arr[0])].concat(arr);
return array
.map((it) => {
return Object.values(it).toString();
})
.join("\n");
};
console.log(
convertToCSV([
{
id: 1,
name: "Foo",
timestamp: new Date(),
},
{
id: 2,
name: "Bar",
timestamp: new Date(),
},
{
id: 3,
name: "Baz",
timestamp: new Date(),
},
])
);
to define the convertToCSV
function.
In it, we create an array
from the property names of the first object in arr
we get from Object.keys
.
We then add the entries off arr
to the end of it with concat
.
Next, we call map
with a callback to get the values of each object with Object.values
and call toString
to convert the array to a comma separated string.
Then we call join
to join each row with a new line.