Categories
JavaScript Answers

How to convert JSON object to CSV format in JavaScript?

Spread the love

Sometimes, we want to convert JSON object to CSV format in JavaScript.

In this article, we’ll look at how to convert JSON object to CSV format in JavaScript.

How to convert JSON object to CSV format in JavaScript>

To convert JSON object to CSV format in JavaScript, we use the 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 get the keys from the first object in the arr array with Object.keys(arr[0]).

Then we put the keys array in an array and call concat with arr.

Next, we call array.map to return the values of the object and return an array of array with the values of each row.

We call toString to return a commas separated string with the values.

And then we call join with '\n' to join the rows together with newline.

Conclusion

To convert JSON object to CSV format in JavaScript, we use the some object and array methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *